【问题标题】:Passing environment variables from json to libraries将环境变量从 json 传递到库
【发布时间】:2019-09-13 20:30:34
【问题描述】:

我有一个 config.json 文件,其中包含我的 angular 7 应用程序的环境变量,然后我将其加载到环境 const 中并且工作正常。 一旦我尝试使用 InjectionTokens 将此环境变量传递给我的新库,就会开始发生奇怪的行为。 我不仅想知道如何解决它,而且如果可能的话,我想知道发生了什么。

我已经尝试了多种导入 json 文件的方法,包括使用 XMLHttpRequest。 还尝试在将对象设置为环境和其他一些东西之前对其进行深度复制。

我的 config.json 文件:

{
  "baseHref": "app",
  "apiEndpoint": "http://localhost:8080/api"
}

我的 environment.prod.ts 文件:

import config from '../config.json';

export const environment = {
  production: true,
  baseHref: config.baseHref,
  apiEndpoint: config.apiEndpoint,
  testing: 'Testing'
};
console.log(environment);

我的 app.module.ts 文件:

imports: [
  TestingModule.forRoot({
    baseHref: environment.baseHref,
    apiEndpoint: environment.apiEndpoint,
    testing: environment.testing,
    production: environment.production
  }),
]

我的 app.module.ts 文件:

export class TestingModule {

  static forRoot(config: any): ModuleWithProviders {
    return {
      ngModule: TestingModule,
      providers: [
        {
          provide: TESTING_CONFIG,
          useValue: config,
        },
      ],
    };
  }

}

我的 testing.service.ts 构造函数:

  constructor(@Inject(TESTING_CONFIG) private config: any) {
    console.log(this.config);
  }

预期所有变量都包含两个控制台日志中的数据,但环境文件第一个包含所有数据,但第二个控制台日志显示 apiEndpoint 为 null 并且测试显示为“正在测试”。

我还尝试调试应用程序,并且在 forRoot 之前它已经拥有环境属性的所有数据。

还注意到,运行这个:

    "aot": true,
    "buildOptimizer": true

在没有这两个选项的情况下运行时有这个问题实际上完全有效。

【问题讨论】:

    标签: json angular typescript environment-variables


    【解决方案1】:

    我找到的解决方案来自以下推导: Angular call function inside forRoot method

    我知道传递一个从环境中解析环境变量的回调:

    export function getConfig() {
      return {
        baseHref: environment.baseHref,
        apiEndpoint: environment.apiEndpoint,
        testing: environment.testing,
        production: environment.production
      };
    }
    
    imports: [
      TestingModule.forRoot(getConfig),
    ]
    

    然后在库中,我现在通过一个工厂执行任何给定的回调。

    export function initializeConfigs(configCallback: any) {
      return configCallback();
    }
    
    export class TestingModule {
    
      static forRoot(config: any): ModuleWithProviders {
        return {
          ngModule: TestingModule,
          providers: [
            {
              provide: 'CONFIG_CALLBACK',
              useValue: config,
            }, {
              provide: TESTING_CONFIG,
              useFactory: initializeConfigs,
              deps: [ 'CONFIG_CALLBACK' ]
            }
          ],
        };
      }
    
    }
    

    这使得 TESTING_CONFIG 注入令牌正确包含所有数据,无需更改环境文件。

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2023-02-12
      • 1970-01-01
      • 2023-02-18
      相关资源
      最近更新 更多