我正在尝试检查我的所有 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(完全上传所有图像),然后就会发生重定向。
最佳答案
更简单的方法是使用 zip
运算符将您的可观察量包装成一个观察量
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);
}
关于javascript - 如何在 forEach 循环中进行同步调用 Angular 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57142714/