I have an Angular project which I compile with AOT. I want to be able to register ClassProvider
that is resolved dynamically according to configuration. Simplified code I use is this:
const isMock = Math.random() > 0.5;
@NgModule({
// ...
providers: [
{ provide: MyServiceBase, useClass: (isMock) ? MyServiceMock : MyService },
],
bootstrap: [AppComponent]
})
export class AppModule { }
The problem is when I compile this with AOT I always get the same service. I would expect to get different service while hitting F5 (because of the randomness
on the first line). When compiling without AOT it behaves as I expect.
Here is the whole code example on github: https://github.com/vdolek/angular-test/tree/aot-conditioned-provider-problem. It behaves differently with ng serve
and ng serve --aot
.
How can I achieve this? I know I could use FactoryProvider
, but then I would have to duplicate the services dependencies (parameters of the factory function and deps property on the FactoryProvider
).