[英]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.