[英]Using MergeMap with the array of data received from another observable - RxJs Angular
[英]Angular - Using mergeMap to fetch data from 2 APIs and saving them in an Array
场景:在 ngOnInit 上,我需要调用 3 个 API,将它们 Fork-Join 并将数据保存在一个数组中。 第一个 API 是独立的。 第二个也是独立的,但第三个取决于第二个 API 的响应。
我以前没有使用过 forkjoin 或 mergemap,我有点困惑。
发生了什么:
我创建了一个通用方法,它采用标识符来确定要命中的端点以及带有所需参数的 object,然后进行响应和错误处理。
服务文件:
callMethod(str, obj, cb?) {
return new Observable(observer => {
this.httpService.getHttpParams(this.URLS_CONSTANT[str], obj, res => {
observer.next(res.data.content ? res.data.content : res.data);
observer.complete();
}, err => { })
})
}
因此,我能够从所有 3 个 API 中获取响应,但 fork-join 后的最终结果包含第一个和第三个 api 的响应。 2nd 的响应不见了,我不知道发生了什么。
这是我写的方法:
fetchAllData() {
let inp = this.input_row;
let response1 = this.service.callMethod('rate_plan', { companyId: inp.cpnyId, servAbbr: inp.servAbbr, productNumber: inp.prdctNo, orgNumber: inp.orgNo, rateCategory: inp.rateCat, ratePlanNumber: inp.ratePlanNo });
let response2 = this.service.callMethod('approve_rate', { prodctNo: inp.prdctNo, servAbbr: inp.servAbbr, companyId: inp.cpnyId, ratePlanNo: inp.ratePlanNo }).pipe(map(item => {
this.approveRate = item
let appRate = item[0]
return appRate
}), mergeMap(data => this.service.callMethod('rate_detail', { companyId: inp.cpnyId, ratePlanNo: inp.ratePlanNo, rateCaseGrpngNo: data['rateCaseGrpngNo']})) )
forkJoin([response1, response2]).subscribe(x => console.log(x))
}
}
最终控制台具有来自 API 调用 1 和 3 的响应值。创建具有三个独立对象的数组需要进行哪些更改。 让我知道是否需要进一步澄清。
您的方法很完美,但是第二个响应可以通过switchMap
运行以获得第三个响应,然后运行在 map 上,以在数组中返回secondResponse
和thirdResponse
的各个值!
fetchAllData() {
let inp = this.input_row;
let response1 = this.service.callMethod('rate_plan', {
companyId: inp.cpnyId,
servAbbr: inp.servAbbr,
productNumber: inp.prdctNo,
orgNumber: inp.orgNo,
rateCategory: inp.rateCat,
ratePlanNumber: inp.ratePlanNo,
});
let response2 = this.service
.callMethod('approve_rate', {
prodctNo: inp.prdctNo,
servAbbr: inp.servAbbr,
companyId: inp.cpnyId,
ratePlanNo: inp.ratePlanNo,
})
.pipe(
switchMap(responsesecond => {
this.approveRate = responsesecond;
let appRate = responsesecond[0];
return this.service
.callMethod('rate_detail', {
companyId: inp.cpnyId,
ratePlanNo: inp.ratePlanNo,
rateCaseGrpngNo: responsesecond['rateCaseGrpngNo'],
})
.pipe(
map(responsethird => {
return [responsesecond, responsethird];
})
);
})
);
forkJoin([response1, response2]).subscribe(x => console.log(x));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.