使用 RxJs 在 Angular 中的错误回调中调用 observable

Calling observable inside an error callback in Angular with RxJs

我有两个相互依赖的 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 发生错误时调用另一个服务,但我不喜欢嵌套订阅。

是否可以在不创建嵌套订阅的情况下做到这一点???

不知道它是否会解决,但你可以用 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 期望一个函数作为参数,该函数本身期望 error 作为输入,return 一个 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 链只有一个订阅。

抓住并释放

如果您仍然希望 source 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(...);