angular使用forRoot() 注册单一实例服务

ShareModule
import { NgModule, ModuleWithProviders } from '@angular/core' ;
@NgModule({
   imports: [
     HttpModule,
     JsonpModule,
     ...
   ],
   declarations: [
     ShowItDirective,
     ...
   ],
   exports: [
     ShowItDirective,
     ...
   ]
})
export class ShareModule{
   // 给shareModule添加forRoot
   static forRoot(): ModuleWithProviders {
     return {
       ngModule: ShareModule,
       providers: [
         MessageService,
         NotifyService,
         ... any service
       ],
     };
   }
}
AppModule
@NgModule({
  declarations: [
   AppComponent,
  ],
  imports: [
   // 使用
   ShareModule.forRoot(),
  ],
  providers: [
   
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

猜你喜欢

转载自www.cnblogs.com/zhenguo-chen/p/13387063.html