How to inject different service based on certain build environment in Angular2?

后端 未结 9 1631
醉话见心
醉话见心 2020-12-04 08:50

I have HeroMockService that will return mocked data and HeroService that will call back end service to retrieve heroes from database.

Assum

9条回答
  •  一整个雨季
    2020-12-04 09:39

    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 {}
    

提交回复
热议问题