3
我需要动态配置一些Angular服务,具体取决于运行时切换。在AOT前几天,我把它用下面的代码工作:动态模块/服务配置和AOT
@NgModule({
imports: [HttpModule],
providers: []
})
export class MyModule {
static forRoot(config: MyConfiguration): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
SomeService,
{
provide: SomeOtherService,
useFactory: (some: SomeService, http: Http) => {
switch (config.type) {
case 'cloud':
return new SomeOtherService(new SomethingSpecificForCloud());
case 'server':
return new SomeOtherService(new SomethingSpecificForServer());
}
},
deps: [SomeService, Http]
},
]
};
}
}
然后在我的AppModule
我会导入此为MyModule.forRoot(myConfig)
。
当我更新CLI和Angular时,不再进行编译,因为它不能被静态分析。我明白为什么,但我仍不确定解决问题的正确方法是什么。
我首先滥用了这个forRoot()
方法吗?如何编写模块,以便根据运行时切换器生成不同的服务?
我认为这是唯一的选择。 1条评论:从v4开始,你应该使用'InjectionToken'而不是'OpaqueToken'。 – mat3e