How to select single item/entity, ngrx?

时间:2018-02-03 07:38:31

标签: angular ngrx ngrx-store ngrx-entity

I have selector to get all posts, actually all entities, now I want to get single post/entity. Should I filter the posts I get from 'getAllPosts' selector or create another one and how to do it ?

Here are my selectors:

export const getPostsState = createFeatureSelector<fromPosts.PostState>('posts');

export const selectAllPosts = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsEntities = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsIds = createSelector(getPostsState, fromPosts.getPostsIds);
export const selectTotal = createSelector(getPostsState, fromPosts.getPostsTotal);
export const selectPostId = createSelector(getPostsState, fromPosts.getSelectedPostId);

export const getSelectedPost = createSelector(selectPostsEntities, selectPostId, (entities, id) => entities[id]);

As you see I have getSelectedPostId and getSelectedPost selectors but I'm not sure how to use it, I tried to follow some tutorials but nothing helps..

1 个答案:

答案 0 :(得分:0)

也许有点晚了,但它可能会帮助某个人。您正在为条目列表和实体使用相同的实体适配器选择器。并且您没有定义要对所选数据执行的操作。 createSelector函数的最后一个参数应始终是具有与前面提到的选择器直接相关的参数的函数,并应返回一些值(通常是参数本身或对其的修改)。

export const selectAllPosts = createSelector(getPostsState, fromPosts.getAllPosts);
export const selectPostsEntities = createSelector(getPostsState, fromPosts.getAllPosts); // <-- see

但是它应该使用selectEntities而不是selectAll。想象一下,您是从这样的实体适配器中获得选择器的,并且实现了自定义ID选择器:

// NgRX entity selectors
const {
  selectIds,
  selectEntities,
  selectAll,
  selectTotal,
} = adapter.getSelectors();

// Custom selector for the selected ID (I guess you have it in the store) and 
// should be the equivalent of your `getSelectedPostId` selector.
const getSelectedId = createSelector(getState, state => state.id);

然后您可以通过以下方式将selectEntitiesgetSelectedId组合在一起:

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

我个人更喜欢将adapter导入选择器,以便您可以在化简器中简单地使用上述语句,并使所有与adapter相关的选择器在需要的地方可用。