首页 > 解决方案 > 如何在forEach循环Angular 6中进行同步调用

问题描述

我正在尝试检查我的所有 4 张图像是否已上传到服务器而没有任何错误,然后重定向到另一个页面,因此我尝试在我的代码中执行一些同步检查(我的imgResultAfterCompress 数组中共有 4 张图像)。下面是我的代码:

if(Boolean(this.updateImage(data.AddId))===true)
    {
     this.router.navigate(['/job-in-hotels-india-abroad']);
    }
updateImage(AddId:number):Observable<boolean> 
{
  this.cnt=0;
  this.uploadingMsg='Uploading Images...';
        this.imgResultAfterCompress.forEach( (value, key) => {

          if(value!=='')
          {

        this.itemService.updateImage(this.employer.ID,AddId,key,value).subscribe(data=>{
          if(data && data.status == 'success') {
            this.uploadingMsg=this.uploadingMsg+'<br>Image No - '+(key+1)+' Uploaded.';  
            this.cnt++;
            }
            else
              this.alertService.error(data.message);

          });
          }
          if(this.cnt==4)
          this.uploadingDone= true;
          else
          this.uploadingDone= false
        }); 
        return this.uploadingDone;
}   

每次我得到cnt值为 0 时,我希望它的值 = 4(完全上传所有图像)然后会发生重定向。

标签: javascriptangulartypescriptangular6

解决方案


zip更简单的方法是使用操作符将你的 observables 包装成一个单一的

https://rxjs-dev.firebaseapp.com/api/index/function/zip

因此,一旦每个请求都成功完成,您的压缩 Observable 将被满足。

更新:

这就是我认为它应该看起来的样子。我可能会错过一些具体的东西,但全球理念应该是明确的

    redirect() {
        this.updateImages(data.AddId).subscribe(
            () => this.router.navigate(['/job-in-hotels-india-abroad']),
            error => this.alertService.error(error.message)
        )
    }


    updateImages(AddId: number): Observable<boolean[]> {
        this.uploadingMsg = 'Uploading Images...';
        const requests: Observable<boolean>[] = [];

        this.imgResultAfterCompress.forEach((value, key) => {
            if (!value) {
                return;
            }

            requests.push(
                this.itemService.updateImage(this.employer.ID, AddId, key, value)
                    .pipe(
                        tap(() => this.uploadingMsg = this.uploadingMsg + '<br>Image No - ' + (key + 1) + ' Uploaded.'),
                        switchMap((data) => {
                            if (data && data.status == 'success') {
                                return of(true)
                            } else {
                                throwError(new Error('Failed to upload image'));
                            }
                        })
                    )
            )
        });
        return zip(...requests);
    }

推荐阅读