这是由于在不同的模块或者应用中使用相同的模块时,使用了懒加载或者预加载(lazy or eager)模式。解决方法是使用 forRoot() 导入共享模块,以确保它可以在整个应用中使用。forRoot() 导入是一种特殊的导入,只能在根模块中使用,在其他地方使用 forFeature() 导入。
代码示例:
在共享模块中,导出 forRoot() 方法
@NgModule({
declarations: [...],
imports: [...],
exports: [...],
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [ExampleService]
}
}
}
在 app.module.ts 中导入共享模块并使用 forRoot() 方法:
@NgModule({
declarations: [...],
imports: [
SharedModule.forRoot(),
...
],
...
})
export class AppModule { }
在其他应用或者模块中可以使用 forFeature() 方法来导入共享模块:
@NgModule({
declarations: [...],
imports: [
SharedModule.forFeature(),
...
],
...
})
export class OtherModule { }