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

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

    This worked for me in Angular 6. Leverages @void's Interface approach (where both the true service and the mock service implement the service interface). The accepted answer neglects to mention that the purpose of a factory is to return an implementation of an interface.

    heroservice/heroservice.module.ts

    import { NgModule, ModuleWithProviders } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { IHeroService } from './ihero.service';
    import { HeroService } from './hero.service';
    import { MockHeroService } from './mock-hero.service';
    
    
    @NgModule({
      imports: [
        CommonModule
      ],
    })
    export class HeroServiceModule {
      static forRoot(mock: boolean): ModuleWithProviders {
        return {
          ngModule: HeroServiceModule ,
          providers: [
            {
              provide: IHeroService,
              useClass: mock ? MockHeroService : HeroService,
            },
          ],
        };
      }
    }
    

    app.module.ts

    import { NgModule, isDevMode } from '@angular/core';
    import { HeroServiceModule } from './heroservice/heroservice.module';
    
    // ...
    
      imports: [
        BrowserModule,
        HttpClientModule,
        // ...
        HeroServiceModule.forRoot(
          isDevMode() // use mock service in dev mode
        ),
      ],
    
    // ...
    

    some/some.component.ts

    Import and use the interface as you would the actual service (the implementation will be "provided" at runtime).

    import { IHeroService } from '../heroservice/iheroservice.service';
    
    // ...
    

提交回复
热议问题