【问题标题】:How to ignore action spam in an effect如何在效果中忽略动作垃圾邮件
【发布时间】:2022-01-15 01:21:30
【问题描述】:

我对 ngrx 比较陌生,并且有一个问题到目前为止我找不到任何答案。

我有一个组件以悲观的方式更新实体的名称属性,这意味着我首先希望在真正更新状态之前获得后端的成功响应。

为此,我使用了 Action 模式,其中我有一个 updateName、updateNameScuccess 和 updateNameFail Action 以及一个 update$ 效果,它将新名称发送到 API 并分派成功或失败的操作。

public updateMyThingsItemName$ = createEffect(() => this.actions$.pipe(
  ofType(
    MyThingsItemActions.updateMyThingsItemName
  ),
  exhaustMap((action) =>
    this.myThingsService.patchMyThingsItem(action.myThingsItem.id, action.myThingsItem.changes).pipe(
      map((myThingsItem) => MyThingsItemActions.updateMyThingsItemSuccess({ myThingsItem })),
      catchError((error: string) => of(MyThingsItemActions.updateMyThingsItemFailure({ error })))
    )
  )
));

我正在使用exhaustMap 运算符,因此如果用户向调度updateMyThingsItemName 操作的更新按钮发送垃圾邮件,我不会向后端发送多个相同的请求。

现在我还有另一个效果,它确实为updateMyThingsItemName 操作提供了一个加载指示器,并且如果更新成功或失败,它会再次关闭指示器:

public presentLoadingSpinner$ = createEffect(() => this.actions$.pipe(
  ofType(
    MyThingsItemActions.updateMyThingsItemName
  ),
  tap(async () => {
    await this.loadingService.presentLoader('loading...');
  })
), {
  dispatch: false
});

因为显示加载微调器的副作用会侦听每个新的updateMyThingsItemName 操作,所以一旦用户向 UI 上发送该操作的按钮发送垃圾邮件,就会创建一个额外的加载微调器。 而且由于该副作用本身不会调度动作,所以我也不能使用排气贴图。

如何编写此效果以忽略动作垃圾邮件?

【问题讨论】:

    标签: ngrx ngrx-effects


    【解决方案1】:

    我认为常见的解决方案是在状态中添加一个加载状态属性。 根据属性,您可以显示/隐藏微调器。

    • Fetch => 设置状态为loading
    • 成功 => 将状态设置为success
    • 错误 => 将状态设置为error

    然后您可以编写一个选择器来检索当前的加载状态,您可以使用它来显示/隐藏微调器。 这有一些变化,但我认为以下一个与您当前的结构相匹配。

    public presentLoadingSpinner$ = createEffect(() => this.store.select(loadingStateSelector),
      filter(loadingState => loadingState === 'loading'),
      tap(async () => {
        await this.loadingService.presentLoader('loading...');
      })
    ), {
      dispatch: false
    });
    

    【讨论】:

    • 我的状态确实有一个 loading 属性,但“问题”是我只想在某些操作上显示微调器。但我想我可以用“微调器”属性来解决它。另一种解决方案可能是为微调器创建一个全局状态作为特性本身并调度 ShowSpinner 操作或类似的东西。但我不确定天气是否是好的架构,因为我是 ngrx 的新手
    猜你喜欢
    • 2011-07-05
    • 2011-04-07
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2014-08-07
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多