NgRX效果catchError和全局错误拦截器

时间:2020-10-22 06:52:25

标签: angular ngrx ngrx-effects

我正在通过catchError使用NgRX效果来返回失败操作,该操作将禁用加载微调器,如下所示:

  update$ = createEffect(() => this.actions$.pipe(
    ofType(update),
    concatMap(({id, data}) =>
      this.dataService.update(id, data).pipe(
        map((voucherOwner: VoucherOwner) => {
          return updateSuccess({voucherOwner});
        }),
        catchError((e: HttpErrorResponse) => {
          return of(updateFailure());
        })
      )
    )
  ));

但是我还使用了一个错误HttpInterceptor来全局捕获状态为500、503等的错误,以显示一个对话框来通知用户出现问题并建议与支持人员联系。

当我用catchError捕获错误时,错误HttpInterceptor不再收到错误。

我需要捕获效果中的错误,以便能够调度失败操作以禁用加载微调器,而且还希望拥有HttpInterceptor来捕获我的状态500错误。我的解决方法是在效果中返回throwError,在失败时返回store.dispatch。如下:

  update$ = createEffect(() => this.actions$.pipe(
    ofType(update),
    concatMap(({id, data}) =>
      this.dataService.update(id, data).pipe(
        map((voucherOwner: VoucherOwner) => updateSuccess({voucherOwner})),
        catchError((e: HttpErrorResponse) => {
          if (e.status === 503 || e.status === 500) {
            this.store.dispatch(updateFailure({}));
            return throwError(e);
          }
          return of(updateFailure());
        })
      )
    )
  ));

由于我认为这很脏,我的问题是是否有更好的解决方案? 例如。类似于同时返回两个值:

return of(updateFailure(), throwError(e)) (我知道,throwError是一个Observable,不能以这种方式使用。)

0 个答案:

没有答案