1

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..

4

1 回答 1

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);

然后您可以通过以下方式将selectEntities与结合起来:getSelectedId

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

就我个人而言,我更喜欢在选择器中导入,adapter这样您就可以在减速器中简单地使用上述语句,并使所有adapter相关的选择器在需要的地方可用。

于 2020-08-19T20:16:36.417 回答