我有以下伪代码:
objects = [obj1, obj2, obj3]
for obj in objects {
user: http.get(obj1.user_id)
product: http.get(obj1.product_id)
}.subscribe(results => {
do something with results
})
我想要的是遍历一个对象数组,对于每个对象,获取相关的用户和产品,然后进行订阅以执行某些操作。如何实现?
我有以下伪代码:
objects = [obj1, obj2, obj3]
for obj in objects {
user: http.get(obj1.user_id)
product: http.get(obj1.product_id)
}.subscribe(results => {
do something with results
})
您可以使用RxJS forkJoin
与Array#map
一起使用,以并行触发多个可观察对象。
const objects = [obj1, obj2, obj3];
forkJoin(
objects.map(obj => // <-- `Array#map` function
forkJoin({
user: http.get(obj.user_id)
product: http.get(obj.product_id)
})
)
).subscribe({
next: (res) => {
console.log(res);
// use `res`
},
error: (err) => {}
});
/*
output in subscription:
[
{
user: result from `http.get(obj1.user_id)`,
product: result from `http.get(obj1.product_id)`,
},
{
user: result from `http.get(obj2.user_id)`,
product: result from `http.get(obj2.product_id)`,
},
{
user: result from `http.get(obj3.user_id)`,
product: result from `http.get(obj3.product_id)`,
}
]
*/
zip()
操作符 来结合你的请求,并在每个请求完成后执行一些代码:const sourceOne = http.get(obj1.product_id);
const sourceTwo = http.get(obj2.product_id);
zip(sourceOne, sourceTwo).subscribe(val => {
// do something
});