角度4 ngModule有条件地注入提供者/服务

时间:2017-09-11 19:14:21

标签: angular dependency-injection

在我的app.module.ts

@NgModule({
...
providers: [MyService,
          // providers used to create fake backend
          fakeBackendProvider,
          MockBackend,
          BaseRequestOptions
         ],
bootstrap: [AppComponent]
})

fakeBackendProvider,MockBackend和BaseRequestOptions用于模拟后端。有没有办法通过environment.ts文件中的变量注入这些服务?

1 个答案:

答案 0 :(得分:0)

你可以像这样使用它。创建了Plunker

//route to environment file
import { environment } from '../../environments/environment';
providers: [MyService,
          // providers used to create fake backend
     {
      provide: SomeSerivce,
      useFactory: authHeadersFactory
    },       
   ],


export function authHeadersFactory() {
  if (environment.prod) {
    return new Mock();
  }
  return new fakeBackend();
}