带有switchMap和catchError的NgRx效果-有人可以解释我的代码与“正确的”代码之间可观察到的工作流程的区别吗?

问题描述 投票:1回答:1

我已将以下代码段发送给代码审查。这种效果需要在请求调用之后分派成功操作,或者如果服务方法抛出错误,则分派错误操作,这非常标准。

@Effect()
  fetchData$ = this.actions$.pipe(
      ofType(ActionTypes.FetchData),
      switchMap(() => {
        return this.dataService.fetchData().pipe(
            map((data: IData): StoreAction<IData> =>
                new FetchDataSuccess(data)),
            catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
      )};
  ));

但是,外部开发人员给了我评论(我没有联系,因此无法要求澄清)。他指示我用另一个switchMap包装我的switchMap(如下面的代码),因为上面代码中第一个switchMap内部的catch错误“将导致效果中断”。

@Effect()
  fetchData$ = this.actions$.pipe(
      switchMap((a: StoreAction<IType>) => of(a).pipe(
          ofType(ActionTypes.FetchData),
          switchMap(() => {
            return this.dataService.fetchData().pipe(
                map((data: IData): StoreAction<IData> =>
                    new FetchDataSuccess(data)),
            );
          }),
          catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
      ))
  );
<

我不了解,我所缺少的是:为什么我们将switchMap包装到另一个switchMap中?在第一种情况下与第二种情况下,有人可以解释这个特殊可观察的工作流程吗?

angular rxjs ngrx ngrx-effects switchmap
1个回答
0
投票
这是无效的,第一个代码段(您如何编写效果)是正确的。

您在内部可观察物(catchError)上有一个this.dataService.fetchData就足够了。如果此处发生错误,则由catchError处理,并且效果将调度操作addErrorValue(error, ErrorCode.FETCH_DATA)

您可以在NgRx example app中看到相同的模式

请参阅https://blog.strongbrew.io/safe-http-calls-with-rxjs/https://medium.com/city-pantry/handling-errors-in-ngrx-effects-a95d918490d9了解更多信息

© www.soinside.com 2019 - 2024. All rights reserved.