慕蓋茨4494581
2023-03-18 17:29:51
如果標題措辭不當,我深表歉意。在我的角度代碼庫中,我可以看到兩個不同的放置請求: public Save() { const types: string[] = this.getTypes.getCurrentTypes(); this.userTypeService .updateTypes(this.userID, groups) .subscribe(() => { showToast("success", "User types Updated."); }); }其中 updateTypes 是一個發出簡單 httpPut 請求的函數。這和使用的重復函數有什么區別.subscribe( showToast("success", "user types updated");)基本上,訂閱中 () => 的功能是什么?另外,有沒有什么好的方法可以使用這種方式從調用中捕獲錯誤?編輯:我想通了,下面的答案對我有用:public Save() { const types: string[] = this.getTypes.getCurrentTypes(); this.userTypeService .updateTypes(this.userID, groups) .subscribe(() => { result => showToast("success", "User types Updated."); error => showToast("error", "Error"); }); }
1 回答

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
.subscribe(
showToast("success", "user types updated");
)
如果刪除分號以修復語法錯誤,那么這將showToast 立即調用并將返回值傳遞給.subscribe. 這種模式唯一有意義的方式是 ifshowToast是一個創建并返回其他函數的工廠函數,但鑒于名稱,我認為這不太可能。假設showToast返回undefined,將不會創建訂閱。
簡而言之:這可能是一個錯誤。
您展示的第一種方法是創建函數并將該函數傳遞給訂閱的正確方法,以便稍后調用它。
有什么好的方法可以從調用中捕獲錯誤
要處理錯誤,您將傳遞第二個函數進行訂閱,告訴它發生錯誤時您想做什么。例如:
.subscribe(
(result) => {
showToast("success", "user types updated")
}, // <--- this function is the same as before, and handles the success case
(error) => {
showToast("failure", error)
} // <--- this function is new and handles the error case.
);
添加回答
舉報
0/150
提交
取消