如果我必须提供更多代码或解释,请告诉我。
我正在尝试执行验证,如果验证不成功,则确认(是/否),然后在 for 循环中为所有选定的行保存方法。
要求:我在遍历所有选定行后显示成功/失败消息。这意味着:
如果选择了 5 行(2 行有效,3 行无效)- 从 myService.validate 获取
它会询问您是否仍要继续 3 个无效记录 - myConfirmService.confirm
它应该保存这 2 条有效记录
如果用户在确认窗口中选择"is"(可以说是 2 条记录),那么它也应该保存这 2 条。
最后 - 它将显示成功/失败消息 - alertService.success
我想要的:
完成我在需求中描述的内容
并且成功/失败消息应该在所有记录保存后只显示一次
组件.ts:
save() {
this.selectRowData.forEach(async s => {
this.myService.validate(s.id).subscribe(data => {
console.log(data);
if(data == false) {
this.myConfirmService
.confirm('Please confirm..', 'Selected Part do not match expected part data. \n Do you still want to continue? ', 'Yes', 'No')
.then((confirmed) => {
if(confirmed) {
console.log("User selected: Yes");
this.myService.savePart();
} else {
console.log("User selected: No");
}
})
.catch(() => {
console.log("Error...");
});
} else {
console.log("Selected Rule matches expected rules for: " + s.designChangeClass);
this.saveModelPart(s);
}
}, (error: any) => {
alert("Error Linking Lot");
});
});
console.log('1st After for loop');
this.alertService.success('Part saved successfully.')
}
service.ts
validate(id: string): Observable < boolean > {
return this.httpClient.get < boolean > ('/RestWeb/validate?id=' + id);
}
validate1(id: string) {
return this.httpClient.get < boolean > ('/RestWeb/validate?id=' + id).toPromise();
}
savePart(item: Part): Observable<any> {
return this.httpClient.post('/RestService/savePart', item);
}
最佳答案
给你。
//Change method to async
async save() {
//Create custom index variable, since for of loop doesn't have one
let ind = 0;
//Use for of instead of forEach
for (const eachRow of this.selectRowData) {
//await until API validated
const isValid = await this.myService.validate(eachRow.id).toPromise();
if (!isValid) {
//await again if it is not valid and until user confirmed
const isConfirmed = await this.myConfirmService.confirm('Please confirm..', 'Selected Part do not match expected part data. \n Do you still want to continue? ', 'Yes', 'No').toPromise();
if (isConfirmed) {
//await again until record saved as user selected yes in confirm
console.log('User selected: Yes');
await this.myService.savePart().toPromise();
} else {
console.log('User selected: No');
}
} else {
console.log(
'Selected Rule matches expected rules for: ' +
eachRow.designChangeClass
);
this.saveModelPart(eachRow);
}
//Finally display message after loop is finished
if (ind === this.selectRowData.length - 1) {
this.alertService.success('Part saved successfully.');
}
ind++;
}
}
虽然这个解决方案可行,但以这种方式进行并不是一个好的做法,
相反,修改 API 以接受多个 ids
进行验证,并显示一个记录表(成功和失败)以及用于确认继续的按钮。
关于angular - 执行所有for循环后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67629174/