Reputation: 49
In my angular app we have a process button that makes calls to the backend service to save data changes for an issue and flips a flag for the issue being read.
I'd like to make my HTTP calls synchronous (wait) so I can determine if the data was saved successfully. If the data was saved successfully we'll display a green material snack-bar and success message. If the call(s) fail we'll display a red material snack-bar with error message.
Originally everything was a subscribe which was async. I did the following based on some articles I came across.
const savedFacilityInfo = this.facility.updateFacilityInfo(this.savedFacilityInfo).toPromise();
savedFacilityInfo.then((data) => {
this.isFacilityInfoSaved = true;
console.log(data);
}).catch((error) => {
console.log(error);
})
const updatedInfo = this.issuesService.updateInfo(this.selectedIssue.issueId, this.savedFacilityInfo).toPromise();
updatedInfo.then((data) => {
this.isUpdated = true;
console.log(data);
}).catch((error) => {
console.log(error);
})
}
if(this.isFacilityInfoSaved && this.isUpdated) {
this.resolvedConfirmation();
} else {
console.log("Display Error");
this.displayErrorConfirmation();
}
This does run, but it doesn't wait for the two service/http calls to finish before evaluating for the resolved or display confirmation.
Am I missing something or is there a better way to handle this?
Upvotes: 0
Views: 100
Reputation: 309
If you need to wait for the two requests, you're better off using forkJoin that will only emit when both Observables complete. If both requests are successful, you'll run the resolvedConfirmation. Otherwise, you'll run displayErrorConfirmation.
forkJoin([
this.facility.updateFacilityInfo(this.savedFacilityInfo),
this.issuesService.updateInfo(this.selectedIssue.issueId, this.savedFacilityInfo)
])
.pipe(catchError(err => {
this.displayErrorConfirmation();
throw EMPTY;
}))
.subscribe([answer1, answer2] => {
this.resolvedConfirmation();
});
Upvotes: 1