【问题标题】:Angular Cli 6 Read Environment NameAngular Cli 6 读取环境名称
【发布时间】:2018-11-21 23:06:54
【问题描述】:

我在我的 angular.json 文件中添加了不同的环境,如此处所述。

https://github.com/angular/angular-cli/wiki/stories-application-environments

当我启动我的应用程序时,例如通过 --configuration=prod 我的 environment.prod.ts 文件被加载。到目前为止一切顺利。

现在我想检查我的组件之一当前选择了哪个环境。但我不知道从哪里可以得到这些信息。一种解决方案是添加一个新属性,例如envName : "envNameXYZ" 到我的每个环境文件,但这容易出错且乏味。

有没有其他解决方法如何获取环境(名称)?

【问题讨论】:

    标签: angular typescript angular-cli-v6


    【解决方案1】:

    最佳解决方案是在每个环境文件中添加一个新属性 envName。 没有其他可能知道环境名称。

    【讨论】:

      【解决方案2】:

      有可用的实验性 isDevMode 功能,但这不会涵盖您制作的自定义功能...

      https://angular.io/api/core/isDevMode

      【讨论】:

        【解决方案3】:

        对于任何对我如何解决它感兴趣的人,这里是我的代码:

        envTypeConfig.ts

        export class EnvTypeConfig {
        
          readonly type: EnvType.TYPE;
        
          constructor(type: EnvType.TYPE) {
            this.type = type;
          }
        
          isStaging() : boolean {
            return this.type == EnvType.TYPE.STAGING;
          }
        }
        
        
        export namespace EnvType {
        
          export enum TYPE {
            DEV = "dev",
            STAGING = "staging",
            FEATURE = "feature",
            PROD = "prod",
          }
        
        
        }
        

        environment.staging.ts

        import {EnvType, EnvTypeConfig} from "./envTypeConfig";
        
        export const environment = {
          envType: new EnvTypeConfig(EnvType.TYPE.STAGING)
        };
        

        在我的组件中,我可以简单地执行以下 sn-p 来检查是否选择了 staging env:

         if(environment.envType.isStaging()){
           console.log("Yippie we are in staging environment!");
         }
        

        【讨论】:

          猜你喜欢
          • 2018-11-23
          • 2018-12-26
          • 2021-10-31
          • 2018-02-19
          • 1970-01-01
          • 1970-01-01
          • 2016-05-02
          • 2019-01-12
          相关资源
          最近更新 更多