我一直试图在DevOps上部署一个Angular 8应用程序,并在.json文件中使用配置,以避免为不同的环境重新构建整个应用程序。
我使用这两个帖子来创建所有配置:
使用Azure DevOps不断将角部署到Azure应用程序服务
堆栈溢出回答:
Note表示,我对使用environment.ts方法不感兴趣,因为这种方式将要求我为每个环境重新构建解决方案。
所以,我准备了所有的代码如下:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: (appConfigService: ConfigService) => {
return () => {
//Make sure to return a promise!
return appConfigService.loadAppConfig();
};
},
deps: [ConfigService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {}我的ConfigService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ConfigService {
private appConfig: any;
constructor(private http: HttpClient) {}
loadAppConfig() {
return this.http.get('./assets/appconfig.json')
.toPromise()
.then(config => {
this.appConfig = config;
});
}
get apiBaseUrl() {
if (!this.appConfig) {
throw Error('Config file not loaded!');
}
return this.appConfig.apiUrl;
}
}然后,需要加载appconfig.json信息的主要对象:
export class ApiService {
apiUrl: string;
constructor(private readonly httpClient: HttpClient,
private configService: ConfigService) {
this.apiUrl = this.configService.apiBaseUrl;
}
ngOnInit() {
this.apiUrl = this.configService.apiBaseUrl;
}
}但是,在加载应用程序时,出现了以下消息:

如果我调试应用程序,appsettings.json文件正在加载信息,但是它看起来就像是在加载应用程序设置之前发生的角度init。
我做错什么了?
发布于 2020-02-07 15:21:57
因此,除了一件重要的事情之外,一切都配置得很好:构造函数只用于注入依赖项。因此,在这一点上,我不能这样说:
constructor(private readonly httpClient: HttpClient,
private configService: ConfigService) {
this.apiUrl = this.configService.apiBaseUrl;
}溶液
然后,我删除了构造函数中的行:
constructor(private readonly httpClient: HttpClient,
private configService: ConfigService) {
}只要我需要它,就给apiBaseUrl打电话,它就起作用了:
public get<T>(url: string): Observable<T> {
return this.httpClient.get<T>(`${this.configService.apiBaseUrl}${url}`);
}发布于 2020-02-07 09:14:21
您可以返回一个Promise并在HTTP请求的subscribe回调中解析它,如下所示:
loadAppConfig() {
return new Promise((resolve) => {
this.http.get('./assets/appconfig.json').subscribe(config => {
this.appConfig = config;
resolve();
})
});
}https://stackoverflow.com/questions/60110257
复制相似问题