【发布时间】:2020-12-17 15:57:30
【问题描述】:
我在 Typescript 中为 Angular 11 编写了一些代码,我需要从一个可观察对象中获取数据,然后循环通过另一个调用来获取名称.获得名称后,我想将其附加到原始对象。
例如我有两个 observables 并且 getSelfPurchases() 返回:
{
id: 32
user_id: 5
script_id: 78
pp_id: "76SDI89768UIHUIH8976"
},
{
id: 33
user_id: 4
script_id: 79
pp_id: "78FGGF78SDF78FSD"
}
第二个,getScriptDetails(32),返回:
{
sname: "Spell Checker"
author: 43
price: 20.99
}
我已经成功地实现了我想做的事情,但我觉得它草率且效率低下。我一直在阅读更多关于 RXJS 的东西,比如 switch map,但我不确定是否可以完成类似的事情。或者也许我选择的方法已经是最好的了。输入?
this.userService.getSelfPurchases().subscribe(response => { // first observable
this.purchases = response;
this.purchases.forEach((purchase, index) => { // loop through our results
this.scriptService.getScriptDetails(purchase.script_id).subscribe(responseTwo => { // second observable
if (responseTwo[0] && responseTwo[0].sname !== undefined) {
this.purchases[index].sname = responseTwo[0].sname; // append to our original purchases object
}
});
});
});
【问题讨论】:
-
是的,你需要 switchMap
标签: angular typescript http rxjs observable