Please let me know if I have to provide any more code or explanations.
I am trying to execute some code after I call a service method inside a for loop. I tried two different ways.
In 1st method, the console.log('1st After for loop') which after the for loop is printing before it prints the console.log(data)
In 2nd method, the console.log('2nd- After for loop') is never printing.
I want to loop through the list. Validate each item. If not validation not successful, show ask for a confirmation. If user selects Yes, the call save method.
Code snippet #1:
save() {
this.selectRowData.forEach(async s => {
this.myService.validate(s.id).subscribe(data => {
console.log(data);
if(data) {
this.myService.confirm('Please confirm..', 'Selected Rule do not match expected rules. \n Do you want to continue? ', 'Yes', 'No')
.then((confirmed) => {
if(confirmed) {
console.log("User selected: Yes");
this.myService.save();
} else {
console.log("User selected: No");
}
}).catch(() => {
console.log("Error...");
});
}, (error: any) => {
alert("Error Linking Lot");
});
});
console.log('1st After for loop');
}
Code snippet #2:
async save() {
await new Promise(resolve => {
this.selectRowData.forEach(async s => {
let validateData = await this.myService.validate1(s.id);
console.log(validateData);
});
});
console.log('2nd- After for loop');
}
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();
}