javascript - 如何等到在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')
});
}
解决方案
您可以使用async
和await
如下
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();
}
}));
推荐阅读
- node.js - 如何将缓冲区从 memoryStorage(multer)转换为图像?
- excel - 更快地比较值的速度改进
- r - 如何在 R 中匹配两个不同的大数据框?
- cross-validation - 当某些迭代具有 NaN 值时,在 mlr3 ResampleResult 中聚合性能度量
- python-3.7 - 使用xlwt如何在excel文件中添加图像
- graylog - Graylog:未显示消息
- spartacus-storefront - 从 smartedit 更改后,斯巴达克斯页面 Id 未解决
- php - PHP 会话在内部不工作 do not include()
- flutter - Flutter:访问存储的 Sharedpreference 值
- r - 如何去掉 R 数据框列名中的引号