【问题标题】:Angular 7 / rxjs - After catchError happens, subscription doesn't receive more valuesAngular 7 / rxjs - 发生 catchError 后,订阅不会收到更多值
【发布时间】:2019-03-08 09:20:20
【问题描述】:

假设我有这个代码:

this.service1
  .getValues()
  .pipe(
    mergeMap(response => this.service2.getMoreValues(response.id)),
    catchError(err => of({}))
  )
  .subscribe(response) => {
    console.log(response)
  });

我的问题是:如果调用了 catchError,我的订阅将不再有新值​​。我想做的是:如果调用了 catchError,我会返回类似空对象的内容并正常进行,但仍期待来自我的服务的新值。

谁能说出为什么在 catchError 被触发后,订阅不再起作用?谢谢。

【问题讨论】:

  • U在mergeMap之后错过了逗号(,)
  • 抱歉,这只是一个例子。我不是要验证上面的代码,我想了解为什么在触发 catchError 后订阅不再起作用的概念。

标签: angular typescript rxjs


【解决方案1】:

这是正确的行为。 catchError 将订阅从其回调返回的 Observable。

这意味着如果你希望它继续从源 Observable 发出值,你可以重新订阅它。

import { concat } from 'rxjs';

const source = this.service1
  .getValues()
  .pipe(
    mergeMap(response => this.service2.getMoreValues(response.id)),
    catchError(err => concat(
      of({}),
      source,
    )),
  );

// Maybe this would work as well, but I didn't test it
// catchError((err, caught) => concat(
//   of({}),
//   caught,
// )),

source.subscribe(response) => {
  console.log(response)
});

最终,retry() 运算符会自动为您重新订阅,但您将无法在重新订阅之前传递 of({})

【讨论】:

    【解决方案2】:

    我想做的是:如果调用 catchError,我会返回类似空对象的东西

    尝试像这样在catchError 中返回of({})

    this.service1
     .getValues()
     .pipe(
       mergeMap(response => this.service2.getMoreValues(response.id)),
       catchError(err => {
         return of({});
       })
     )
     .subscribe(response) => {
       console.log(response)
     });
    

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 2021-12-07
      • 1970-01-01
      • 2023-03-12
      • 2021-10-25
      • 2021-12-22
      相关资源
      最近更新 更多