【发布时间】: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