問題描述
需要幫助了解這種 Ngrx 效果 (Need help understanding this Ngrx effect)
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
使用 of(action)
在手動構造的 Observable 中。不會
參考解法
方法 1:
Your suggestions should work fine, if you just need the selected state:
concatMap(() => this.store.select(selectSelectedBookIds).pipe(first())),
However, should you also need the action itself, the following will pass along an array containing both the action and your selected state:
concatMap(action => of(action).pipe(
withLatestFrom(this.store.select(fromBooks.getCollectionBookIds))
)),
(by Neutrino、Steve Holgado)