Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

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

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

Assuming Angular2 has build environment, I'm planning to inject HeroMockService to AppComponent if current build environment is "dev-mock". If current build environment is "dev-rest", HeroService should be injected to AppComponent instead.

I would like to know how can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...