【问题标题】:ngrx effect - catchError: returning of does not end stream, and the API call does not re-runngrx 效果 - catchError: 返回的不结束流,并且 API 调用不重新运行
【发布时间】:2021-06-11 10:32:19
【问题描述】:

我在NgRX效果中有个效果,如下:

$createOrganisation = createEffect(() =>
  this.actions$.pipe(
    ofType(fromOrganisationActions.createOrganisation),
    switchMap((data) => this.organisation.createOrganisation(data)),
    map((response) => fromOrganisationActions.createOrganisationSuccess({ orgId: response.id })),
    catchError((error) => {
      return of(fromOrganisationActions.createOrganisationError(error));
    })
  )
);

但是,当catchError 被触发时,我的流似乎永远不会结束,即在this.organisation.createOrganisation 的实例中返回 400 错误。

动作,fromOrganisationActions.createOrganisationError(error) 被触发,我的 reducer 也由此触发...但是如果我重新触发 fromOrganisationActions.createOrganisation 效果,这个效果会运行,但不会再次调用 API。

如果我按如下方式配置它,并手动调度它,它就可以工作:

$createOrganisation = createEffect(() =>
  this.actions$.pipe(
    ofType(fromOrganisationActions.createOrganisation),
    switchMap((data) => this.organisation.createOrganisation(data)),
    map((response) => fromOrganisationActions.createOrganisationSuccess({ orgId: response.id })),
    catchError((error) => {
      this.store.dispatch(fromOrganisationActions.createOrganisationError(error));
      return throwError(error);
    })
  )
);

但是网上的其他例子表明第一种方法应该可行,但它不适合我,我不明白为什么我的流永远不会结束。

有人可以建议并告诉我为什么我的直播一开始就永远不会结束吗?

【问题讨论】:

    标签: rxjs ngrx angular-httpclient ngrx-effects


    【解决方案1】:

    catchError 应该添加到内部 observable 中。

    $createOrganisation = createEffect(() =>
      this.actions$.pipe(
        ofType(fromOrganisationActions.createOrganisation),
        switchMap((data) => this.organisation.createOrganisation(data).pipe (
          map((response) => 
            fromOrganisationActions.createOrganisationSuccess({ orgId: response.id })),
          catchError((error) => {
            return of(fromOrganisationActions.createOrganisationError(error));
          })
        )),
      )
    );
    

    这些错误可以通过eslint-plugin-ngrx 捕获,更多关于规则here 的详细信息。

    【讨论】:

    • 不错。谢谢!在内部可观察对象上使用 catchError 之间的实际区别是什么?在这种情况下,我认为可观察的结果是相同的?我现在正在安装那个插件!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2020-08-23
    • 2023-02-16
    • 2011-09-30
    • 1970-01-01
    • 2021-12-20
    • 2021-08-05
    相关资源
    最近更新 更多