如何嵌套封装在APP_INITIALIZER中的httpclient调用



我已经实现了一个由APP_INITIALIZER触发的httpCall,它返回一个URL,然后我想将其用于另一个嵌套的httpCall:

getAppSettings(): Observable<IAppSettings> {
return (this.httpClient
.get<IAppSettings>(this.localbaseUrl)
.pipe(
catchError(this.errorHandlerSerevice.handleError)
)) as any;
}
getConfigValues(): Promise<void> {
return this.getAppSettings()
.toPromise()
.then(data => {
this.exampleUrl = data;
this.getOtherStuff().subscribe(data => this.stuff = data);
});
}
getOtherStuff(): Observable<any[]> {
return (this.httpClient
.get<any[]>(this.exampleUrl)
.pipe(
catchError(this.errorHandlerSerevice.handleError)
)) as any;
}

这个实现是错误的,在页面刷新时会抛出以下错误:

Uncaught (in promise): TypeError: Cannot read property 'length' of undefined

它来自于this.stuff[]没有及时填充(第二个,嵌套的httpClient可观察调用(。

如何正确实现/嵌套那些httpClient调用。请注意,我使用的是Angular 6和httpClient,请不要建议使用旧的http-get解决方案。

事实证明,您不能在APP_INITIALIZER初始化的Promise中嵌套Observable。嵌套调用也需要是Promise。查看修改后的方法,现在可以正确分配this.stuff:

getConfigValues(): Promise<void> {
return this.getAppSettings()
.toPromise()
.then(data => {
this.exampleUrl = data;
}).then(() => {
return this.getOtherStuff()
.toPromise()
.then(data => { 
this.stuff = data; 
});
}
);
}

相关内容

最新更新