I have HeroMockService
that will return mocked data and HeroService
that will call back end service to retrieve heroes from database.
Assum
If you organize your code into Angular2 modules, you can create an additional module to import mocked services, for example:
@NgModule({
providers: [
{ provide: HeroService, useClass: HeroMockService }
]
})
export class MockModule {}
Assuming that you declare import for normal services in your core module:
@NgModule({
providers: [ HeroService ]
})
export class CoreModule {}
As long as you import MockModule
after CoreModule
, then the value that will be injected for HeroService
token is HeroMockService
. This is because Angular will use the latest value if there are two providers for the same token.
You can then customize import for MockModule
based on certain value (that represents build environment), for example:
// Normal imported modules
var importedModules: Array = [
CoreModule,
BrowserModule,
AppRoutingModule
];
if (process.env.ENV === 'mock') {
console.log('Enabling mocked services.');
importedModules.push(MockModule);
}
@NgModule({
imports: importedModules
})
export class AppModule {}