I need to have some Angular services configured dynamically, depending on a runtime switch. In days before AOT, I got it to work using the following code:
@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]
},
]
};
}
}
Then in my AppModule
I would import this as MyModule.forRoot(myConfig)
.
As I updated CLI and Angular, this no longer compiles, because it cannot be statically analyzed. I understand why, but I am still not sure what the correct way to solve it is.
Have I abused this forRoot()
approach in the first place? How do you write modules so that depending on a runtime switch, they produce different services?