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

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

相关内容

热门资讯

外挂操作!poker worl... 外挂操作!poker world辅助,哈糖大菠萝万能挂-确实一直总是有辅助技巧(哔哩哔哩)1、在哈糖...
外挂指引!哈糖大菠萝挂,红龙p... 外挂指引!哈糖大菠萝挂,红龙poker辅助平台-确实存在有辅助方法(哔哩哔哩)一、红龙poker辅助...
外挂经验!xpoker辅助控制... 外挂经验!xpoker辅助控制,xpoker透视辅助-原来一直总是有辅助工具(哔哩哔哩);1、用户打...
外挂演示!约局吧辅助器,agp... 外挂演示!约局吧辅助器,agpoker辅助-一直一直都是有辅助教程(哔哩哔哩)1、约局吧辅助器免费脚...
外挂课程!拱趴大菠萝开挂方法,... 外挂课程!拱趴大菠萝开挂方法,pokerrrr2辅助-确实存在有辅助工具(哔哩哔哩)暗藏猫腻,小编详...
外挂模板!uupoker有透视... 外挂模板!uupoker有透视吗,约局吧开挂神器是真的吗-一直真的是有辅助方法(哔哩哔哩)1、约局吧...
外挂教材!佛手在线大菠萝辅助,... 外挂教材!佛手在线大菠萝辅助,拱趴大菠萝万能辅助器-都是是真的有辅助攻略(哔哩哔哩)外挂教材!佛手在...
外挂演示!德州私人局脚本,po... 外挂演示!德州私人局脚本,pokermaster修改器-竟然存在有辅助攻略(哔哩哔哩)德州私人局脚本...
外挂项目!xpoker辅助控制... 外挂项目!xpoker辅助控制,pokernow辅助控制-本来真的是有辅助方法(哔哩哔哩)所有人都在...
外挂办法!哈糖大菠萝开挂,德普... 外挂办法!哈糖大菠萝开挂,德普之星私人局辅助免费-原来一直总是有辅助教程(哔哩哔哩)哈糖大菠萝开挂是...