javascript - 如何在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(完全上传所有图像)然后会发生重定向。
解决方案
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);
}
推荐阅读
- macos - 在 Mac Catalina 中安装旧版本的 ilibmobiledevice ( libimobiledevice.6.dylib )
- autodesk-forge - 选定的组件在 Forge Viewer 中发光
- python - 将python 3.8中的变量分配给shell命令
- sql - 如果不存在,则使用正确的列顺序创建索引
- javascript - 刷新从 MySQL 填充的数据表,而不每 x 秒刷新整个页面
- android - Android:从 API 29 中的现有 URI 覆盖文件
- vue.js - 父子之间的双向数据绑定
- .htaccess - htaccess 用不同的文件访问重写 url 路径
- python - 划分列表元素并将它们附加到新列表
- appium - WebDriverAgent 文件夹缺少 appium 1.15.1