首页 > 解决方案 > 如何等到在Angular内部有多个服务调用的for循环

问题描述

我希望仅在 for 循环完成整个执行后才停止加载程序,

我有一个循环,我在其中调用元数据服务来获取条件检查的所有数据,并根据我调用保存服务的条件。

我想等到所有保存服务完成后再停止加载程序并显示常见的成功消息并处理错误。

save(data) {
  data.forEach(element => {
    if(element.isCreatable){
      forkJoin(this.http.getMetaData(element)).subscribe(values => {
        //condition checks
        //20 lines of code to check condition
        //if condition fulfills call save service
        if (condition) {
            forkJoin(this.http.submitData(val)).subscribe(res => {
                if (res) {
                    //success message
                    //stop loader
                }
            });
        }
    });
    } 
  });
}

更新感谢 BizzyBob,我尝试了提供的答案,但它抛出错误“您提供了未定义的流预期位置”。

function save1(data) {
  forkJoin(
    data
      .filter(val => val.isCreatable)
      .map(e => {
        console.log(e); //coming as object 
        this.http.getMetaData(e).pipe(
          switchMap(meta => {
          //20 lines of code to check condition
            if (condition) {
              return this.http.submitData(meta);
            } else {
              return EMPTY;
            }
          })
        );
      })
  ).subscribe({
    complete: () => console.log('stop loader')
  });
}

标签: javascriptangularrxjs

解决方案


您可以使用asyncawait如下

async save(data) {
    await Promise.all(data.map(async element => {
      if (element.isCreatable) {
        await this.http.getMetaData(element).pipe(switchMap(values => {
          //condition checks
          //20 lines of code to check condition
          //if condition fulfills call save service
          if (condition) {
            return this.http.submitData(val).pipe(tap(res => {
              if (res) {
                //success message
                //stop loader
              }
            }));
          }
          return EMPTY;
        })).toPromise();
      }
    }));

推荐阅读