[英]Angular: How to build agnostic of environment?
I'm trying to update my codebase so that regardless of the environment the variables used will work. 我正在尝试更新我的代码库,以便无论环境如何,所使用的变量都将起作用。 Angular's
angular.json
has the ability to add environment specific configurations. Angular的
angular.json
能够添加特定于环境的配置。 In addition to that, I'd like to know if and how it's possible to use the environment specific variables with specific environment configs and not have to actually build for a different environment. 除此之外,我想知道是否以及如何使用特定环境配置的环境特定变量,而不必实际构建不同的环境。 So that when promoting builds I don't have to build for that specific environment.
因此,在推广构建时,我不必为特定环境构建。
I tried doing it off of the window.location
, but I couldn't get that to work. 我尝试从
window.location
做到这一点,但我无法让它工作。 Any ideas/help appreciated. 任何想法/帮助表示赞赏。
// env.ts
const local = {
x: '',
y: '',
z: ''
};
const stg = {
x: '',
y: '',
z: ''
};
const prd = {
x: '',
y: '',
z: ''
};
// angular.json
"configurations": {
"local": {
// ...local
},
"stg": {
// ...stg
},
"production": {
// ... prod
}
}
I found this article which ultimately was the solution for scenario. 我发现这篇文章最终是方案的解决方案。 Compile-time vs. Runtime configuration of your Angular App
Angular App的编译时与运行时配置
The APP_INITIALIZER allows to defer the “booting” of your module, normally the AppModule.
APP_INITIALIZER允许推迟模块的“启动”,通常是AppModule。 If you're curious how this is implemented behind the scenes, well Angular is open source, so you can just go and read the source 😉.
如果你很好奇这是如何在幕后实现的,那么Angular是开源的,所以你可以去阅读源 😉。
// AppConfigService
import {
Injectable
} from '@angular/core';
import {
HttpClient
} from '@angular/common/http';
@Injectable()
export class AppConfigService {
private appConfig;
constructor(private http: HttpClient) {}
loadAppConfig() {
return this.http.get('/assets/data/appConfig.json')
.toPromise()
.then(data => {
this.appConfig = data;
});
}
getConfig() {
return this.appConfig;
}
}
// app.module.ts
...
import {
NgModule,
APP_INITIALIZER
} from '@angular/core';
import {
AppConfigService
} from './app-config.service';
const appInitializerFn = (appConfig: AppConfigService) => {
return () => {
return appConfig.loadAppConfig();
};
};
@NgModule({
...
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [AppConfigService]
}
],
...
})
export class AppModule {}
Some other interesting discussion on this subject Runtime Environment Settings , Angular Application Environments 关于此主题的一些其他有趣的讨论运行时环境设置 , 角度应用程序环境
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.