为了解决这个问题,我们需要在共享模块中提供一个服务提供程序,以确保所有懒加载模块使用相同的服务实例。
首先,在共享模块中创建一个服务:
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 { }
这样,我们就保证了懒加载模块使用与共享模块相同的服务实例。