首页 > 解决方案 > Angular - 检查列表中的所有订阅者是否都已完成

问题描述

我使用间隔在 forEach 循环中将可变数量的数据发布到后端。我想要做的是:如果 post 方法的第一次调用没有完成但间隔已经想第二次调用该方法,则应该阻塞调用,直到第一次调用完成。

我尝试在代码中显示这一点

setInterval(() => {
  console.log('pendingServiceDataRequests', this.pendingServiceDataRequests);
  if(/* if pendingServiceDataRequests is empty or all subscriber are finished */){
   this.sendData();
  }
}, 5000);


sendData(){
  serviceList = [/* some data */]
  serviceList.forEach((service, index, array) => {
    const currentSub = this.api.post(url, service).subscribe((res: any) => {
            /* delete successful send data */
    }
    this.pendingDataRequests.push(currentSub);
   });
 }

我将所有订阅者放在一个列表中,但我不知道如何检查所有请求是否已完成

标签: angularpostforeachangular5subscriber

解决方案


对于这种情况,ConactMap 将是正确的。尝试这个:

sendData() {
    serviceList = [/* some data */]
    return from(serviceList).pipe(
        concatMap(id => <Observable<Item>> this.api.post(url, service)
    );
}

https://blog.angularindepth.com/practical-rxjs-in-the-wild-requests-with-concatmap-vs-mergemap-vs-forkjoin-11e5b2efe293


推荐阅读