在我的 Angular 應用程式中,我們有一個行程按鈕,它呼叫后端服務來保存問題的資料更改,并為正在讀取的問題翻轉一個標志。
我想讓我的 HTTP 呼叫同步(等待),這樣我就可以確定資料是否保存成功。如果資料保存成功,我們將顯示綠色材料小吃欄和成功訊息。如果呼叫失敗,我們將顯示帶有錯誤訊息的紅色材料小吃欄。
最初一切都是異步的訂閱。我根據我遇到的一些文章做了以下作業。
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();
}
這確實會運行,但在評估已解決或顯示確認之前,它不會等待兩個 service/http 呼叫完成。
我錯過了什么還是有更好的方法來處理這個?
uj5u.com熱心網友回復:
如果你需要等待這兩個請求,你最好使用只在兩個 Observables 完成時才會發出的 forkJoin。如果兩個請求都成功,您將運行resolvedConfirmation。否則,您將運行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();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409350.html
標籤:
