首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何嵌套封装在APP_INITIALIZER中的httpclient调用

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

Stack Overflow用户
提问于 2018-11-15 13:04:55
回答 1查看 278关注 0票数 2

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

代码语言:javascript
复制
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;
}

此实现是错误的,在页面刷新时会引发以下错误:

代码语言:javascript
复制
 Uncaught (in promise): TypeError: Cannot read property 'length' of undefined

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

如何正确地实现/嵌套这些httpClient调用。请注意,我使用角6和httpClient,请不要建议旧的http获取解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-15 15:18:02

结果发现,你不能在APP_INITIALIZER初始化的承诺中嵌套一个可以观察到的东西。嵌套调用也需要承诺。请参见修改后的方法,该方法现在正确分配了this.stuff:

代码语言:javascript
复制
getConfigValues(): Promise<void> {
    return this.getAppSettings()
        .toPromise()
        .then(data => {
            this.exampleUrl = data;
        }).then(() => {
                return this.getOtherStuff()
                    .toPromise()
                    .then(data => { 
                            this.stuff = data; 
                    });
            }
        );
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53320136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档