模塊A是這樣定義的app
@NgModule({ providers: [AService], declarations: [ TitleComponent ], exports: [ TitleComponent ], }) export class A {}
若是有惰性模塊lazyModule導入模塊A,那麼會生成子注入器將AService從新生成ide
這時若是想將AService變成全局惟一的,那麼在lazyModule導入的時候就不要導入providers而只導入TitleComponentspa
forRoot這時就有用武之地了code
改寫Ablog
@NgModule({ providers: [], declarations: [ TitleComponent ], exports: [ TitleComponent ], }) export class A { static forRoot() { return {ngModule: A, providers: [AService]}; } }
在appModule中使用A.forRoot導入A模塊it
@NgModule({ imports: [A.forRoot()] }) export class AppModule {}
在lazyModule中正常導入A模塊io
@NgModule({ imports: [A] }) export class LazyModule{}