I need to replace a service with a mock service depending on an environment variable. To do this, I used the ?-operator in the provider area within my module like this:
@NgModule({
imports: [
...
],
providers: [
...
environment.e2e ? { provide: MyService, useClass: MyServiceMock} : MyService
],
})
export class DemoModule {
}
This approach works so far - if the 'e2e' variable is true the mock is used, otherwise the real service is loaded. There is a problem with this solution, however. If I build in production mode (with e2e=false), then the code of the mock is still included in the compiled bundle. I tried also to replace the Service via factory inside the injectable decorator. When using this solution, the service gets replaced in the right way, but the mock is again present in production bundle.
@Injectable({
providedIn: 'root',
useFactory: (dep1, dep2) => environment.e2e ? new MyServiceMock(dep1, dep2) : new MyService(dep1, dep2),
deps: [dep1, dep2]
})
export class MyService {
...
}
Does anyone know a way how I can replace the service depending on the environment and the mock service also doesn't end up in the production bundle?