Angular app\u初始值设定项上的app init之后加载appsettings.json文件
我一直在尝试在DevOps上部署Angular 8应用程序,并在.json文件中使用配置,以避免为不同的环境重新构建整个应用程序 我使用这两篇文章来创建所有配置: 和堆栈溢出回答: 请注意,我对使用environment.ts方式不感兴趣,因为这种方式需要我为每个环境重新构建解决方案 因此,我准备的所有代码如下:Angular app\u初始值设定项上的app init之后加载appsettings.json文件,angular,angular8,angular2-services,Angular,Angular8,Angular2 Services,我一直在尝试在DevOps上部署Angular 8应用程序,并在.json文件中使用配置,以避免为不同的环境重新构建整个应用程序 我使用这两篇文章来创建所有配置: 和堆栈溢出回答: 请注意,我对使用environment.ts方式不感兴趣,因为这种方式需要我为每个环境重新构建解决方案 因此,我准备的所有代码如下: @NgModule({ declarations: [ AppComponent ], imports: [ BrowserMo
@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 {}
My ConfigService.ts:
然后,需要加载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文件正在加载信息,但看起来像是在加载appsettings之前发生了角度初始化
我做错了什么?您可以返回一个承诺,并在HTTP请求的订阅回调中解决它,如下所示:
loadAppConfig() {
return new Promise((resolve) => {
this.http.get('./assets/appconfig.json').subscribe(config => {
this.appConfig = config;
resolve();
})
});
}
所以,除了一件重要的事情之外,所有的东西都配置得很好:构造函数只用于注入依赖项。因此,在这一点上,我不能这样说:
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}`);
}
不确定要更改哪些文件。。。。正如您所说,我更改了loadAppConfig,并返回了一个承诺,但不知道还有什么需要更改并使其生效。您能否创建一个项目来重现该问题,以便我可以进一步帮助您?我修复了项目中的一些错误。我发现stackblitz目前不支持对本地文件的HTTP请求,所以我将其替换为占位符。它正在工作:那么apiUrl是未定义的。。。因此,在应用程序初始化期间不会加载它。那是我的问题。在本地我没有错误,可能是我没有使它正常工作,但确切的问题是hello.component没有正确加载APIRL。请注意,第一个console.log为我加载数据的工作方式是相同的,但是,当您尝试在hello.component上访问它时,您没有该数据。您知道为什么它没有加载到APP_初始值设定项上吗?这在Angular 8中仍然适用于您吗?加载我的配置文件时出现问题。
public get<T>(url: string): Observable<T> {
return this.httpClient.get<T>(`${this.configService.apiBaseUrl}${url}`);
}