angular-cli: Conditional Imports using an environment variable

后端 未结 2 598
情书的邮戳
情书的邮戳 2020-12-06 17:23

Is there a way to conditionally change imports based on an environment variable in angular-cli@1.0.0-beta.16? I\'m trying to do it in a way that doesn\'t require code change

2条回答
  •  清歌不尽
    2020-12-06 18:07

    You're going about it completely wrong. Angular can handle this use case with the use of factories when you configure the providers

    providers: [
      Any,
      Dependencies
      {
        provide: MyService, 
        useFactory: (any: Any, dependencies: Dependencies) => {
          if (environment.production) {
            return new MyService(any, dependencies);
          } else {
            return new MockMyService(any, dependencies);
          }
        },
        deps: [ Any, Dependencies ]
    ]
    

    Now you can just inject MyService everywhere because of the provide: MyService, but in development, you will get the mock, and in production you will get the real service.

    See Also:

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

提交回复
热议问题