angular – 如何使用@ngrx / entity通过id选择单个对象

使用@ngrx / entity我希望通过实体映射中的id数组按单个id或实体数组选择实体.

当实体集合获取新元素或实体项目发生更改时,我不希望触发组件内的选择订阅,我根本没有选择.

当我使用selectEntities选择器然后从结果中选择ID时,这显然发生在我身上.

那么如何从实体集合中按ID选择1个或n个项目?

最佳答案 NgRx支持参数化选择器
passing props as the last argument to a selector function

export const selectEntity = createSelector(
  selectEntities,
  (entities, props) => entities[props.id]
);

export const selectEntitiesByID = createSelector(
  selectEntities,
  (entities, props) => props.ids.map(id => entities[id])
);

完全按照您的预期调用它们:

this.store.pipe(
  select(selectEntity, { id: someID })
);

this.store.pipe(
  select(selectEntitiesByID, { ids: arrayOfIDs })
);

如果您的ID不会更改,您可以将这些ID重构为工厂功能:

export const selectEntity = id => createSelector(
  selectEntities,
  entities => entities[id]
);

export const selectEntitiesByID = ids => createSelector(
  selectEntities,
  entities => ids.map(id => entities[id])
);

因此被称为:

this.store.pipe(
  select(selectEntity(someID))
);

this.store.pipe(
  select(selectEntitiesByID(arrayOfIDs))
);
点赞