[NgRx] NgRx Entity Adapter Configuration - Understanding sortComparer and selectId

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[NgRx] NgRx Entity Adapter Configuration - Understanding sortComparer and selectId相关的知识,希望对你有一定的参考价值。

import  Course, compareCourses  from "../model/course";
import  EntityState, createEntityAdapter  from "@ngrx/entity";
import  createReducer, on  from "@ngrx/store";
import  CoursesAction  from "../actions-types";
/*
export interface CoursesState 
  entities:  [key: number]: Course ;
  ids: number[];
*/

export interface CoursesState extends EntityState<Course> 
  /**Extend the entity here */
  allCoursesLoaded: boolean;


export const adapter = createEntityAdapter<Course>(
  sortComparer: compareCourses
  // selectId: course => course.id // NgRx use ‘id‘ by default
);

export const initCoursesState = adapter.getInitialState(
  allCoursesLoaded: false
);

export const coursesReducer = createReducer(
  initCoursesState,
  on(CoursesAction.allCoursesLoaded, (state, action) =>
    adapter.addAll(action.courses,  ...state, allCoursesLoaded: true )
  )
);

export const  selectAll  = adapter.getSelectors();

 

export function compareCourses(c1:Course, c2: Course) 

  const compare = c1.seqNo - c2.seqNo;

  if (compare > 0) 
    return 1;
  
  else if ( compare < 0) 
    return -1;
  
  else return 0;

 

‘sortCompoarer‘ is used with adapter when you want to sort the entites based on one prop, ‘ids‘ will be also sorted accordingly to the new entities.

以上是关于[NgRx] NgRx Entity Adapter Configuration - Understanding sortComparer and selectId的主要内容,如果未能解决你的问题,请参考以下文章

ngrx/entity 中的 SelectAll 不选择任何内容

NgRX实体:ID在州内未定义

安装@ngrx/store 时如何清除错误?

如何使用 ngrx-router-store 在 ngrx 效果中获取路由参数?

NgRx @Effect 与 createEffect

ngrx 调度的动作未达到效果