Looking for a way to dynamically replace a service with a mock service based on an environment variable? I've been using the ?-operator in the provider section of my module like this:
@NgModule({
imports: [
...
],
providers: [
...
environment.e2e ? { provide: MyService, useClass: MyServiceMock} : MyService
],
})
export class DemoModule {
}
While this method functions as intended - switching between the mock and real service based on the 'e2e' variable - it does come with a downside. When building in production mode (with e2e=false), the code for the mock service still gets included in the compiled bundle. I also attempted to replace the Service using a factory within the @Injectable decorator. Although this approach correctly swaps out the service, the mock service ends up in the production bundle once again.
@Injectable({
providedIn: 'root',
useFactory: (dep1, dep2) => environment.e2e ? new MyServiceMock(dep1, dep2) : new MyService(dep1, dep2),
deps: [dep1, dep2]
})
export class MyService {
...
}
Does anyone have insights on how to replace a service based on the environment without including the mock service in the production bundle?