Angular 6:如何识别forkJoin响应 [英] Angular 6 : How to identify forkJoin response

查看:107
本文介绍了Angular 6:如何识别forkJoin响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角度6:如何使用 forkJoin

reqs = [];
if (shouldUpdatePhone) {
   reqs.push(this.customerService.updatePhone(phoneUpdateRequest))
}
if (shouldUpdateAddress) {
   reqs.push(this.customerService.updateAddress(addressUpdateRequest))
}

forkJoin(reqs).subscribe(result => {
   console.log('result :', result);
  //How to know response is from updatePhone and response from updateAddress?
});

如何识别收到的响应属于updatePhone和updateAddress?基于标识,我需要向用户显示消息.

How to can i identify response received is belong to updatePhone and updateAddress? based on identification i need to show message to user.

这两个api返回 Array(2)>

{型号:true,代码:200,消息:空},

{型号:true,代码:200,消息:空}

推荐答案

您可以在每个请求之后使用map管道将响应包装在另一个标识响应类型的对象中.就是这样:

You can wrap your reponses in another object that identifies their type by using the map pipe after each request. Just like this:

reqs = [];
if (shouldUpdatePhone) {
    reqs.push(this.customerService.updatePhone(phoneUpdateRequest)
        .pipe(map(value => ({type: 'phone', value: value})))
        .pipe(catchError(value => of({type: 'phone', failed: true}))))
}
if (shouldUpdateAddress) {
    reqs.push(this.customerService.updateAddress(addressUpdateRequest)
        .pipe(map(value => ({type: 'address', value: value})))
        .pipe(catchError(value => of({type: 'address', failed: true}))))
}

forkJoin(reqs).subscribe(results => {
    console.log('result :', results);

    for(let result of results){
        if(result.type == 'phone'){
            if(result.failed)
                console.log("Phone failed");
            else
                console.log("Phone: " + result.value);
        }

        else if(result.type == 'address'){
            if(result.failed)
                console.log("Address failed");
            else
                console.log("Address: " + result.value);
        }
    }
});

这篇关于Angular 6:如何识别forkJoin响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆