See below my solution is based on @peeskillet one.
Create an interface that both the mock and real service implement, for your example IHeroService
.
export interface IHeroService {
getHeroes();
}
export class HeroService implements IHeroService {
getHeroes() {
//Implementation goes here
}
}
export class HeroMockService implements IHeroService {
getHeroes() {
//Mock implementation goes here
}
Assuming you've created the Angular app using Angular-CLI, in your environment.ts
file add the appropriate implementation, e.g.:
import { HeroService } from '../app/hero.service';
export const environment = {
production: false,
heroService: HeroService
};
For every different environment.(prod|whatever).ts
you have to define a heroService
pointing to the implementation and add the import.
Now, say you want to import the service in the AppModule class (you can do it on the component where you need the service as well)
@NgModule({
declarations: [
AppComponent,
],
imports: [
FormsModule,
HttpModule,
AlertModule.forRoot()
],
providers: [
{
provide: 'IHeroService',
useClass: environment.heroService
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
The important part is the provider:
providers: [
{
provide: 'IHeroService',
useClass: environment.heroService
}
Now wherever you want to use the service you have to do the following:
import { IHeroService } from './../hero.service';
export class HeroComponent {
constructor(@Inject('IHeroService') private heroService: IHeroService) {}
Sources:
Is it possible to inject interface with angular2?
https://medium.com/beautiful-angular/angular-2-and-environment-variables-59c57ba643be
http://tattoocoder.com/angular-cli-using-the-environment-option/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…