首页 > 解决方案 > 需要帮助了解这种 Ngrx 效果

问题描述

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 }
    );

该示例已更改为 use concatLatestFrom,但这在这里并不重要。我感兴趣的是理解最初的建议。我想我理解意图,以避免在源操作触发时withLatestFrom处理结果getCollectionBookIds,但我不明白为什么解决方案需要涉及withLatestFrom使用of(action). 这样的东西不是同样有效并且更具可读性吗?

    concatMap(() => this.store.select(selectSelectedBookIds).pipe(first())),

我对 Rxjs 的理解不是很好,经过几天的尝试,我怀疑我仍然错过了一些东西。

标签: rxjsngrxngrx-storengrx-effects

解决方案


如果您只需要选定的状态,您的建议应该可以正常工作:

concatMap(() => this.store.select(selectSelectedBookIds).pipe(first())),

但是,如果您还需要操作本身,以下将传递一个包含操作和您选择的状态的数组:

concatMap(action => of(action).pipe(
  withLatestFrom(this.store.select(fromBooks.getCollectionBookIds))
)),

推荐阅读