Angular NGRX: multiple Entities in one EntityAdapter possible?

喜欢而已 提交于 2019-12-04 02:06:30

NgRx entity is a simple and small library to handle large arrays even thought the documentation does not explain how to use more than one entity in one state, it should be easy since the library what it does behind the scenes is just normalize the array and create a dictionary with the data.

In order to make work the state with one or more entities follow the next steps:

Start by defining a state of each entity.

interface CarState extends EntityState<Car> {
  total: number;
}

interface PlaceState extends EntityState<Place> {
  total: number;
}

Then create a state that holds the entities

export interface State {
  msg: string;
  cars: CarState;
  places: PlaceState;
}

Create the adapters for each entity state to manipulate the data and create the initial states.

const adapterCar = createEntityAdapter<Car>();
const adapterPlace = createEntityAdapter<Place>();

const carInitialState: CarState = adapterCar.getInitialState({ total: 0 });
const placeInitialState: PlaceState = adapterPlace.getInitialState({ total: 0 });

Define the initial global state

const initialState = {
  msg: 'Multiple entities in the same state',
  cars: carInitialState,
  places: placeInitialState
}

Create the reducer:

export function reducer(state: State = initialState, action: ExampleActions): State {

  switch (action.type) {

    case ExampleActionTypes.GetCarList:
      return { ...state, cars: adapterCar.addMany(action.payload, state.cars) };

    case ExampleActionTypes.GetPlaceList:
      return { ...state, places: adapterPlace.addMany(action.payload, state.places) };

    default:
      return state;
  }

}

Expose the selectors

export const selectCarState = (state: State) => state.cars;
export const selectPlaceState = (state: State) => state.places;

export const { selectAll: selectAllCars } = adapterCar.getSelectors();
export const { selectAll: selectAllPlaces } = adapterPlace.getSelectors();

That's it :)

Live example: https://stackblitz.com/edit/angular-multiple-entities-in-same-state

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