I have HeroMockService that will return mocked data and HeroService that will call back end service to retrieve heroes from database.
Assum
This worked for me in Angular 6. Leverages @void's Interface approach (where both the true service and the mock service implement the service interface). The accepted answer neglects to mention that the purpose of a factory is to return an implementation of an interface.
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IHeroService } from './ihero.service';
import { HeroService } from './hero.service';
import { MockHeroService } from './mock-hero.service';
@NgModule({
imports: [
CommonModule
],
})
export class HeroServiceModule {
static forRoot(mock: boolean): ModuleWithProviders {
return {
ngModule: HeroServiceModule ,
providers: [
{
provide: IHeroService,
useClass: mock ? MockHeroService : HeroService,
},
],
};
}
}
import { NgModule, isDevMode } from '@angular/core';
import { HeroServiceModule } from './heroservice/heroservice.module';
// ...
imports: [
BrowserModule,
HttpClientModule,
// ...
HeroServiceModule.forRoot(
isDevMode() // use mock service in dev mode
),
],
// ...
Import and use the interface as you would the actual service (the implementation will be "provided" at runtime).
import { IHeroService } from '../heroservice/iheroservice.service';
// ...