我有兩個相互依賴的 observable 呼叫,這很好用,但是一旦回應中發生錯誤,我需要呼叫另一個可回滾事務的 observable。
Z那是我的代碼:
return this.myService.createOrder()
.pipe(
concatMap((res: MyResponse) => this.addProduct(res.orderId, PRODUCT_ID))
).subscribe({
error: (error: any): void => // TODO: Call another observable here passing res.orderId to rollback transaction
});
正如您在TODO 中看到的,我的計劃是在發生錯誤時呼叫另一個服務res.orderId,但我不喜歡嵌套訂閱。
是否可以在不創建嵌套訂閱的情況下做到這一點???
uj5u.com熱心網友回復:
不知道它是否會解決,但您可以嘗試使用CathError嗎?
return this.myService.createOrder().pipe(
concatMap((res: MyResponse) => this.addProduct(res.orderId, PRODUCT_ID)),
catchError((res: MyResponse) => {
// Call here your observable with res
})
).subscribe(console.log);
uj5u.com熱心網友回復:
正如@Emilien 指出的那樣,catchError在這種情況下是你的朋友。
catchError期望作為引數的函式本身期望error作為輸入并回傳一個Observable。
所以,代碼看起來像這樣
// define a variable to hold the orderId in case an error occurs
let orderId: any
return this.myService.createOrder().pipe(
tap((res: MyResponse) => orderId = res.orderId),
concatMap((res: MyResponse) => this.addProduct(res.orderId, PRODUCT_ID)),
catchError((error: any) => {
// this.rollBack is the function that creates the Observable that rolls back the transaction - I assume that this Observable will need orderId and mybe the error to be constructed
// catchError returns such Observable which will be executed if an error ouucrs
return this.rollBack(orderId, error)
})
).subscribe(console.log);
如您所見,在這種情況下,整個 Observable 鏈只有一個訂閱。
uj5u.com熱心網友回復:
捕捉和釋放
如果您仍然希望源 observable 出錯。您可以捕獲錯誤,運行回滾可觀察物件,然后在完成后重新拋出錯誤。
這可能看起來像這樣:
this.myService.createOrder().pipe(
concatMap((res: MyResponse) => this.addProduct(res.orderId, PRODUCT_ID).pipe(
catchError(err => concat(
this.rollBack(res.orderId),
throwError(() => err)
)
)
).subscribe(...);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390669.html
上一篇:當angular條件為真時取消訂閱observable
下一篇:帶表格的角表格
