[英]Calling observable inside an error callback in Angular with RxJs
我有兩個相互依賴的可觀察調用,這工作正常,但是一旦響應中發生錯誤,我需要調用另一個可觀察的來回滾事務。
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
發生錯誤時調用另一個服務,但我不喜歡嵌套訂閱。
是否可以在不創建嵌套訂閱的情況下做到這一點???
不知道它是否會解決,但您可以嘗試使用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);
正如@Emilien 所指出的,在這種情況下, catchError
是您的朋友。
catchError
期望 function 作為參數,它本身期望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 鏈只有一個訂閱。
如果您仍然希望源 observable 出錯。 您可以捕獲錯誤,運行您的回滾 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(...);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.