拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 使用RxJs在Angular中的错误回呼中呼叫observable

使用RxJs在Angular中的错误回呼中呼叫observable

白鹭 - 2022-01-24 1966 0 0

我有两个相互依赖的 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(...);
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *