【问题标题】:Dispatching multiple conditional actions调度多个条件动作
【发布时间】:2019-03-27 00:07:35
【问题描述】:

我正在尝试设计一个可以查看对象列表的 ngrx 效果。如果一个 id 在这个列表中,它需要用新的 Id 更新 reducer 并导航到一个新的路由。

如果 id 不在列表中,它只需要导航到新路线。此条件路径有效。 NavigateToNewApp(newPath) 将成功路由到新路径。

(concatMap) 的返回,需要触发两个动作 - SetThingIdSuccess 和 NavigateToNewInternalApp 不起作用。我得到:UserEffects.setAppContext" dispatched an invalid action: {"_isScalar":true}。如果我脱掉 of,那简直是未定义的。

有没有更好的方法来构建这个?从ngrx中的条件语句发送多个效果的最佳方式是什么?

@Effect()
setAppContext = this.actions$.pipe(
  ofType(UserActionTypes.DoAPermittedThing),
  withLatestFrom(
    this.store$.select(getPermittedThingIDs),
    this.store$.select(getPermittedThings)
  ),
  map(([thingID, permittedThingIDs, permittedThings]) => {
    if (permittedThingIDs.find(id => (thingID as any).payload === id) < 0) {
      const newPath = permittedThings[0].Path;
      return new NavigateToNewApp(newPath);
    }
    return of(
      concatMap(() => {
        const currentId = (thingID as any).payload as number;
        return [new SetThingIdSuccess(currentId), new NavigateToNewInternalApp()];
      })
  })
);

【问题讨论】:

    标签: angular ngrx


    【解决方案1】:

    Austin 在Dispatching Multiple Actions from NGRX Effects 中写过这篇文章

    我们如何解决这个问题?让我们打破 switchMap 以返回一个新的 具有多个动作的可观察数组!

    @Effect() save = this.update$.pipe(
       map(action => action.payload),
       switchMap(payload => this.myService.save(payload)),
       switchMap(res => [
           new Notification('save success'),
           new SaveSuccess(res)
       ])
    );
    

    在你的情况下,我认为你不应该使用map,而应该使用concatMap,并且总是返回一个包含你的操作的数组。

    【讨论】:

    • 谢谢。顺便说一句,不错的 ngx-testing-library!
    【解决方案2】:

    我建议在此效果中,如果需要设置SetThingIdSuccess 操作,则返回该操作,然后为返回NavigateToNewInternalAppSetThingIdSuccess 创建一个新效果。它不必发生在相同的效果中,并且导航是成功操作的副作用,因此将其分解是有意义的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多