首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >forkJoin Angular 5的MergeMap问题

forkJoin Angular 5的MergeMap问题
EN

Stack Overflow用户
提问于 2018-08-01 16:33:33
回答 1查看 862关注 0票数 0

我正在尝试用mergeMap和forkJoin有条件地执行5个并行的http请求。对我来说,只有第一个api会被执行,其余的api不会触发。

我的函数将执行第一个api,如果它返回状态为'NOT_FOUND',那么我需要执行另外5个api,并需要返回最终结果。如果我得到的状态不同于'NOT_FOUND',只需要从第一个http请求中返回observable。我尝试了不同的选项,但似乎都不起作用。在共享代码下面,我得到了"ERROR TypeError: Unable to get property 'map‘of undefined or null reference“

代码语言:javascript
复制
public myPostWrapper( url, body, flag): Observable<any> {
 return this.http.post( url, body, { headers: this.headers } )
        .map(( out: any ) => {
            console.log( 'out', JSON.stringify( out ) );
            this.result = out;
        } )
        .mergeMap(( response: any ) => {
            console.log( 'response-inside', JSON.stringify( response ) );
            if ( this.result.status === 'NOT_FOUND' ) {
                return Observable.forkJoin(
                    response.map(( resp: any ) => {
                        return this.http.post(url, body, { headers: this.headers })
                            .map(( res: any ) => {
                                const section: any = res;
                                return section;
                            } );
                    } ),
                    response.map(( resp: any ) => {
                        return this.http.post(url, body, { headers: this.headers })
                            .map(( res: any ) => {
                                const section: any = res;
                                return section;
                            } );
                    } )
                );
            } else {
                return Observable.of( this.result );
            }
        } )
        .catch(( error: any ) => Observable.throw( error || 'Server error' ) 
);

}

任何帮助/指导都将不胜感激。注意:我正在使用Rxjs 5.52和Angular 5

EN

回答 1

Stack Overflow用户

发布于 2018-08-01 16:38:37

在设置this.result的第一个map中,不返回任何内容。这意味着,链的以下部分将在undefined上运行。在第一个map操作中添加return out;,这应该可以解决您的问题。

代码语言:javascript
复制
...
return this.http.post( url, body, { headers: this.headers } )
    .map(( out: any ) => {
        console.log( 'out', JSON.stringify( out ) );
        this.result = out;
        return out; // <--- This return here
    } )
...

您可以选择将mergeMap中出现的所有response替换为this.result

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51628761

复制
相关文章

相似问题

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