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 { }

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

相关内容

热门资讯

透视好牌!拱趴大菠萝机器人,p... 透视好牌!拱趴大菠萝机器人,pokemmo免费脚本(果然有挂);一、拱趴大菠萝机器人软件透明挂的定义...
aapoker辅助工具存在!a... aapoker辅助工具存在!aapoker有猫腻吗,(aapokEr)一直存在有挂,详细教程(有挂详...
透视透视!德州透视脚本,竞技联... 透视透视!德州透视脚本,竞技联盟破解版最新版(好像有挂);1、操作简单,无需注册,只需要使用手机进行...
aapoker辅助工具存在!a... aapoker辅助工具存在!aapoker有什么规律吗,(AAPOKEr)竟然是有挂,详细教程(有挂...
透视美元局!拱趴大菠萝挂哪里,... 透视美元局!拱趴大菠萝挂哪里,pokemomo辅助工具(竟然存在有挂);1、拱趴大菠萝挂哪里ai机器...
aapoker有挂!德州aa辅... aapoker有挂!德州aa辅助,(Aapoker)原来有挂,详细教程(有挂总结)是一款可以让一直输...
aapoker辅助工具!aa扑... 这是一款非常优秀的aapoker辅助工具 ia辅助检测软件,能够让你了解到aapoker辅助工具中牌...
透视辅助!哈糖大菠萝怎么开挂,... 透视辅助!哈糖大菠萝怎么开挂,epoker有透视吗(好像真的有挂);1、在哈糖大菠萝怎么开挂ai机器...
透视代打!哈糖大菠萝软件下载,... 透视代打!哈糖大菠萝软件下载,菠萝德普辅助器免费版在哪里(果然是有挂)1、该软件可以轻松地帮助玩家将...
aapoker有外 挂!德州a... aapoker有外 挂!德州aapoker下载,(aApoker)其实真的有挂,详细教程(有挂技巧)...