首页 > 解决方案 > 如何在带有来自动作的道具(MemoizedSelectorWithProps)的选择器的效果中使用 withLatestFrom

问题描述

我有一个带有道具的选择器(类型为 MemoizedSelectorWithProps)。我想在 WithLatestFrom 中的效果中使用它。问题是 - 选择器(道具)的参数来自动作有效负载。而且我无法让 withLatestFrom 访问操作有效负载。

我正在使用 angular 7(自然是 ngrx7)。我尝试使用地图以某种方式创建一个新的可观察对象,但没有任何效果......

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

行动:

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 - 也可以随意提出建议。

标签: javascriptangulartypescriptrxjsngrx

解决方案


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

例如:

@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...
  })
)

推荐阅读