Я уже пытался прочитать официальную документацию и не очень хорошо ее понял.
Я хотел бы сделать две вещи:
- Вернуть человека with isMain true;
- Правильно структурируйте архитектуру с помощью селекторов;
У меня есть сомнения относительно того, как вернуть этого конкретного человека, и у меня также есть сомнения относительно того, как правильно структурировать диспетчеризация этого селектора в архитектуре.
РЕДУКТОР ЛЮДЕЙ:
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { People } from '@shared/interfaces/people.interface';
import * as fromPeopleAction from './people.actions';
export interface State extends EntityState<People> {}
export const adapter: EntityAdapter<People> = createEntityAdapter<People>({
selectId: (people: People) => people.id,
});
const INIT_STATE: State = adapter.getInitialState({
data: null,
error: null,
loading: false,
});
export function reducer(state = INIT_STATE, action: fromPeopleAction.Actions) {
switch (action.type) {
case fromPeopleAction.ActionTypes.CREATE:
return adapter.addOne(action.payload.people, {
...state,
data: action.payload.people,
loading: true,
});
case fromPeopleAction.ActionTypes.CREATE_SUCCESS:
return adapter.addOne(action.payload.people, state);
case fromPeopleAction.ActionTypes.CREATE_FAIL:
return adapter.addOne(action.payload.people, {
...state,
error: action.payload.error,
loading: false,
});
default:
return state;
}
}
УСЛУГИ ЛЮДЕЙ
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { People } from '@app/shared/interfaces/people.interface';
import { StoreState } from '@app/store/index';
import * as fromPeopleActions from '@app/store/people/people.actions';
import * as fromPeopleSelectors from '@app/store/people/people.selectors';
@Injectable({ providedIn: 'root' })
export class PeopleService {
people$: Observable<Array<People[]>>;
constructor(private store: Store<StoreState>) {}
get(peopleId: string): any {
this.store.dispatch(new fromPeopleActions.PeopleGet());
}
create(people: People): any {
this.store.dispatch(new fromPeopleActions.PeopleCreate({ people }));
}
update(people: Partial<People>): any {
this.store.dispatch(new fromPeopleActions.PeopleUpdate({ id: people.id, changes: people }));
}
}
ВЫБОРЫ ЛЮДЕЙ
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { State, adapter } from './people.reducer';
const featureSelector = createFeatureSelector<State>('people');
export const { selectIds, selectEntities, selectAll, selectTotal } = adapter.getSelectors(featureSelector);
export const getMainPeople = createSelector(featureSelector, (state: State) => {
state.ids.forEach((id: any) => {
if (state.entities[id].isMain) {
return state.entities;
}
});
});