在 OnInit 你需要有一个数组:
let finalArray = [
{code:7865, price:203, color: red},
{code:8865, price:303, color: pink},
...]
从对 url1 的请求中,我们得到一个对象数组,其中对象的数量,从它的每个 id 中,我们对 url2 进行额外的请求,我们得到 'price' 和 'color' 的值。
如果代码来自 url1,如何收集带有代码、价格和颜色的整个对象?
finalArray = [];
this.httpService.getDataFromServer(url1)
.pipe(
map(resp => {
// здесь приходит 'code'
const ordersArray = [];
for (const items of resp) {
ordersArray.push(items.id);
}
return ordersArray;
}),
switchMap(data => {
return forkJoin(
data.map((order) => {
return this.httpService.getDataFromServer(url2 + '/' + order);
})
);
})
).subscribe(resp => {
const arr = [];
for (const patient of resp) {
const object = {};
object['price'] = patient.price;
object['color'] = patient.color;
arr.push(object);
}
this.finalArray = arr;
});
事实上,解决这个问题的选择并不多,其中一个是在请求之前缓存在上面声明的一些变量中,另一个选项是使用流映射使一切更具反应性:
不幸的是,我不知道你的模型和你的服务器返回什么,所以我随机做了一点,从你的代码中做出假设,如果有的话 - 取消订阅。