网站搜索

javascript - 我如何在带有来自动作的 props(MemoizedSelectorWithProps)的选择器的 effect 中使用 withLatestFrom


我有一个带有属性(类型为 MemoizedSelectorWithProps)的 selector。我想在 WithLatestFrom 内的 effect 中使用它。问题是 - selector 的参数(属性)来自 action 的 payload。而且我无法让 withLatestFrom 访问 action 的 payload。

我正在使用 Angular 7(当然还有 ngrx7)。我尝试过使用 map 来以某种方式创建一个新的 observable,但什么都不管用...

这些是我在这里写的一些演示行,以简化我的使用情况:

动作 :

export const GET_INVENTORY = '[App] Get Inventory';

export class GetInventory implements Action {
  readonly type = GET_INVENTORY;
  constructor (public branchId: number) {} 
}

效果 :

@Effect()
getInventory$ = this.actions$.pipe(
  ofType(GET_INVENTORY)
  withLatestFrom(this.store$.pipe(select(getIsStoreInventoryLoaded, {branchId: action.branchId}))), // this is not working obviously, since action is unknown
  switchMap([action, loaded]: [GetInventory, boolean] => {
  if (loaded) {
    console.log('already loaded inventory for this branch', action.branchId);
  } else {
    console.log('never loaded inventory for this branch', action.branchId);
  }
}

虽然这是我代码的简化版本,但在我的实际项目中设计大致相似——我有一个按“分店”配置的库存存储。例如,我是假设一个连锁超市,每个分店都有自己的库存页面,有大量数据,如果我已经获取过数据,就不想再次获取。所以如果你有不同的方法,而不是使用 MemoizedSelectorWithProps,也可以随意建议。

答案#1

一个简单的switchMap或者带有combineLatest的mergeMap应该可以解决问题。

例如:

@Effect()
getInventory$ = this.actions$.pipe(
  ofType(GET_INVENTORY),
  mergeMap(action =>
    combineLatest(
      of(action),
      this.store$.pipe(select(getIsStoreInventoryLoaded, {branchId: action.branchId}))
    )
  ),
  tap(([action, loaded]) => {
    // The rest of your code...
  })
)