例如,我有多个ids : [1,2,3,4,5]
,然后对于每个id,我都要调用delete api端点。通常情况下,我必须用forEach函数调用它5次:
ids.forEach(item => {
this.myService.delete(item).subscribe.....
})
但是,如果我想把它组合成一个可观察的,这样我就可以知道循环何时结束(rxjs中的完整状态(,该怎么办?
我能做这样的事吗?
您可以首先创建可观察器的数组,然后使用forkJoin
并行执行它们!
deleteIds(ids: Array<number>) {
// create a array of delete observables to be executed at once
const deleteIds = ids.map(id => this.myService.delete(id));
forkJoin(deleteIds).subscribe(() => {
// execute the rest of the code
});
}
我想您也可以使用zip运算符来完成此操作
deleteIds(ids: Array<number>) {
// create a array of delete observables to be executed at once
const deleteIds = ids.map(id => this.myService.delete(id));
zip(...deleteIds).subscribe(() => {
// execute the rest of the code
});
}