【问题标题】:pass data from state to new action in rxjs effect在 rxjs 效果中将数据从状态传递到新动作
【发布时间】:2020-05-12 07:26:03
【问题描述】:

我想访问状态数据以将结果作为新操作的属性传递。在触发效果后,我设法从状态中提取所需的数据,但使用数据调度新操作的最后部分不起作用。我不能将activeUseractiveTask 这两个参数传递给最后一行代码中的of(GetInstances({activeUser, activeTask})) 部分。

@Effect()
updateInstanceLabelSuccess$ = this._actions$.pipe(
  ofType<Action>(EInstanceActions.UpdateInstanceLabelSuccess),
  concatMap(action => of(action).pipe(
    withLatestFrom(combineLatest(
      [this._userStore.pipe(select(selectActiveUser)),
        this._userStore.pipe(select(selectActiveTask))]
    ))
  )),
  tap(([action, [activeUser, activeTask]]: [Action, [User, Task]]) => {
    console.log(activeUser, activeTask);
    // activeUer and activeTask successfully loaded
    // pass activeUser + activeTask to props of Action GetInstances
  }),
  // activeUser and activeTask can´t be passed to new GetInstances Action
  switchMap(([action, [activeUser, activeTask]]: [Action, [User, Task]]) => of(GetInstances({activeUser, activeTask})))
);

如何将activeUseractiveTask 这两个参数传递给新的GetInstances Action?

编辑:

我得到它使用以下代码。这是解决问题的有效方法吗?

@Effect()
updateInstanceLabelSuccess$ = this._actions$.pipe(
  ofType<Action>(EInstanceActions.UpdateInstanceLabelSuccess),
  concatMap(action => of(action).pipe(
    withLatestFrom(combineLatest(
      [this._userStore.pipe(select(selectActiveUser)),
      this._userStore.pipe(select(selectActiveTask))]
    ))
  )),
  map(([action, [activeUser, activeTask]]: [Action, [User, Task]]) => GetInstances({userID: activeUser.id, taskID: activeTask.id}))
);

【问题讨论】:

  • 您收到错误消息还是该操作没有任何有效负载?
  • 对于更新后的问题:您的实现对我来说似乎很好,现在很好用 :)

标签: typescript rxjs ngrx


【解决方案1】:

该代码看起来很棒,并且是一种完全有效的方法。

除非我遗漏了什么,否则我认为您可以清理以下内容:

@Effect()
updateInstanceLabelSuccess$ = this._actions$.pipe(
    ofType<Action>(EInstanceActions.UpdateInstanceLabelSuccess),
    withLatestFrom(
        this._userStore.pipe(select(selectActiveUser)),
        this._userStore.pipe(select(selectActiveTask)),
        (action, activeUser, activeTask) => [activeUser, activeTask]
    ),
    map(([activeUser, activeTask]): [User, Task]) => GetInstances({userID: activeUser.id, taskID: activeTask.id}))
);

我在这里所做的只是利用 withLatestFrom 的重载,包括最终投影函数,我发现它在您不想携带无关动作的情况下很有用。

另一个建议是创建一个新的选择器,将您拥有的这两个选择器结合起来。我知道这听起来有点矫枉过正,但由于选择器结果的内置缓存,这样做会给您带来一点性能优势。

无论如何,我希望这会有所帮助。很好地解决了这个问题。

【讨论】:

  • 您的代码看起来很干净,运行良好,谢谢您的提示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 2011-02-11
  • 2021-08-29
  • 1970-01-01
相关资源
最近更新 更多