Angular懒加载模块从共享库中获取单独的服务实例
创始人
2024-10-27 22:00:53
0

为了解决这个问题,我们需要在共享模块中提供一个服务提供程序,以确保所有懒加载模块使用相同的服务实例。

首先,在共享模块中创建一个服务:

shared.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  constructor() { }
  
  // Your service methods here
}

接下来,在共享模块中导出ServiceProvider:

shared.module.ts

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedService } from './shared.service';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  exports: []
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [SharedService]
    };
  }
}

现在,我们可以将SharedModule的forRoot方法添加到应用程序的根模块中:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    SharedModule.forRoot(),
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在,我们可以将SharedService添加到懒加载模块的providers数组中:

lazy.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { LazyComponent } from './lazy.component';
import { SharedService } from '../shared/shared.service';

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([{
      path: '',
      component: LazyComponent
    }])
  ],
  declarations: [LazyComponent],
  providers: [SharedService]
})
export class LazyModule { }

这样,我们就保证了懒加载模块使用与共享模块相同的服务实例。

相关内容

热门资讯

第5分钟解迷!透视辅助功能插件... 第5分钟解迷!透视辅助功能插件下载,新漫游正版辅助软件(其实真的有挂)-哔哩哔哩1、透视辅助功能插件...
六分钟关于!四川途游辅助软件,... 六分钟关于!四川途游辅助软件,新518互游插件下载(好像真的是有挂)-哔哩哔哩1、四川途游辅助软件机...
第6分钟详情!指尖四川辅助脚本... 第6分钟详情!指尖四川辅助脚本苹果版,宁夏划水辅助(一直是真的挂)-哔哩哔哩1、上手简单,内置详细流...
第7分钟分享!wepoker辅... 第7分钟分享!wepoker辅助工具,雀友会广东潮汕辅助(原来是有挂)-哔哩哔哩1、雀友会广东潮汕辅...
2分钟解密!老友广西玩有破解视... 2分钟解密!老友广西玩有破解视频,花花生活圈怎么开挂(原来真的有挂)-哔哩哔哩1、下载好老友广西玩有...
第9分钟了解!心悦透明器看手机... 第9分钟了解!心悦透明器看手机纸牌,掌中乐游戏辅助工具(本来有挂)-哔哩哔哩1.心悦透明器看手机纸牌...
一分钟教你!同城游辅助工具,中... 一分钟教你!同城游辅助工具,中至赣州黑科技辅助软件(果然是有挂)-哔哩哔哩;1、起透看视 中至赣州黑...
4分钟解谜!胡乐辅助脚本可靠吗... 您好,胡乐辅助脚本可靠吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多...
第6分钟科普!茶馆儿破解教程,... 第6分钟科普!茶馆儿破解教程,开心游戏辅助器(一贯存在有挂)-哔哩哔哩1、下载好开心游戏辅助器辅助软...
2分钟了解!微乐小程序免费黑科... 2分钟了解!微乐小程序免费黑科技下载,微信小程序微乐辅助器(其实真的有挂)-哔哩哔哩1、下载好微乐小...