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

后端 未结 9 1645
醉话见心
醉话见心 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:35

    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/

提交回复
热议问题