ngrx parameter to select function

╄→尐↘猪︶ㄣ 提交于 2019-12-25 11:55:03

问题


Is there a way to pass parameters to ngrx select functions?

Following is my use case:

I am maintaining list of comments in store.

I wrote one component to represent one comment. So, one CommentComponent knows the id of the component object

Each comment will have properties like likedBy, reportedBy, ...etc In UI, I am showing all the components using *ngFor

Now I want my CommentComponent to subscribe only to one comment object by using id of the component.

Right now I am subscribing to all the comments in a top level component, and passing each comment to the CommentCompoent as an input.

Current approach is not clean because angular change detection strategy (even if I use onPush) has to render DOM for all the comments even though only one comment changes.

Appreciate any suggestions where I can pass comment id to a selector function so that each CommentComponent can subscribe to only one comment.

Thanks in advance, Sudhakar


回答1:


As of NgRx 6.1, you can use a selector with props.

export const getCount = () =>   
  createSelector(     
    (state, props) => state.counter[props.id],     
    (counter, props) => counter * props.multiply
);

For more info and different ways, check out my article NgRx: Parameterized selectors




回答2:


Yes, you can pass parameters to the ngrx selector and you can do that in this way

from the component side

this.store.select(getComments(user_id));

from the selector side

export const getComments = (user_id) => createSelector(
  getData,
  (store) => store.comments 
);


来源:https://stackoverflow.com/questions/46109044/ngrx-parameter-to-select-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!