问题描述
Ngrx 文档,用于使用从商店中选择的状态的效果 状态(无双关语)
Note: For performance reasons,use a flattening operator like concatMap to prevent the
selector from firing until the correct action is dispatched.
...并提供示例:
addBookToCollectionSuccess$ = createEffect(() => this.actions$.pipe(
ofType(CollectionApiActions.addBookSuccess),concatMap(action => of(action).pipe(
withLatestFrom(this.store.select(fromBooks.getCollectionBookIds))
)),tap(([action,bookCollection]) => console.log('whatever'))
),{ dispatch: false }
);
此示例已更改为使用 concatLatestFrom
,但这在这里并不重要。我感兴趣的是理解最初的建议。我想我理解意图,以避免除了源操作触发时 withLatestFrom
处理结果,但我不明白为什么解决方案需要将 getCollectionBookIds
包装在使用 withLatestFrom
手动构建的 Observable。像这样的东西会不会同样有效且更具可读性?
of(action)
我对 Rxjs 的理解不是很好,在尝试解决这个问题几天后,我怀疑我仍然遗漏了一些东西。
解决方法
如果您只需要选定状态,您的建议应该可以正常工作:
concatMap(() => this.store.select(selectSelectedBookIds).pipe(first())),
但是,如果您还需要操作本身,以下将传递一个包含操作和您选择的状态的数组:
concatMap(action => of(action).pipe(
withLatestFrom(this.store.select(fromBooks.getCollectionBookIds))
)),