【问题标题】:RxJs. How to throw error and continue emiting values if I have a two observable?RxJs。如果我有两个 observable,如何抛出错误并继续发出值?
【发布时间】:2021-12-27 04:39:37
【问题描述】:

https://stackblitz.com/edit/rxjs-catcherror-withmapoperators-lwutxg?file=index.ts

const fakeRequest$ = of().pipe(
  tap((_) => console.log('fakeRequest')),
  throwError
);

const iWillContinueListening$ = fromEvent(
  document.getElementById('continued'),
  'click'
).pipe(
  switchMap((_) =>
    fakeRequest$.pipe(
      catchError((_) => {
        return throwError('x');
      })
    )
  )
);

const parent = iWillContinueListening$.pipe(
  catchError((err) => {
    console.log('er', err);
    return of('err');
  })
);



parent.subscribe(console.log);

如何在 iWillContinueListening$ 出错时激活 catchError on parrent 并仍然发出值?

【问题讨论】:

标签: error-handling rxjs try-catch rxjs-observables rxjs-pipeable-operators


【解决方案1】:

为了查看你想要达到的效果,你的iWillContinueListening$ observable 永远不应该抛出错误。它应该捕获错误并返回一个备用值。

const iWillContinueListening$ = fromEvent(
  document.getElementById('continued'),
  'click'
).pipe(
  switchMap((_) =>
    fakeRequest$.pipe(
      catchError((_) => {
        //return throwError('x'); <--commenting this
        return of('x');  <-- adding this
      })
    )
  )
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2019-10-09
    • 2018-07-05
    • 1970-01-01
    相关资源
    最近更新 更多