Let's say I have a state AnimalState
that looks like this:
{
cats: Cat[];
dogs: Dog[];
}
Here how the reducers are defined :
export const catsReducer = createReducer([],
on(AnimalAction.loadCats,
(state, { cats }) => {
return {
...state,
cats
};
}),
);
export const dogsReducer = createReducer([],
on(AnimalAction.loadDogs,
(_, { dogs }) => {
return dogs;
}),
);
export const reducers: ActionReducerMap<AnimalState> = {
cats: catsReducer,
dogs: dogsReducer,
};
I then inject reducers into my custom module with an InjectionToken such as :
const reducerToken = new InjectionToken<ActionReducerMap<AnimalState>>(
'ANIMAL_REDUCERS',
{ factory: () => reducers });
StoreModule.forFeature("animal", reducerToken),
My question is how can I create and register a reducer that will use both cats
and dogs
values.
Well you would want to split the reducer and initial states:
const initialCatState: Cat[] = []
export const catsReducer = createReducer(initialCatState,
on(CatAction.update,
(state, { cats }) => {
return cats;
}),
);
const initialDogState: Dog[] = []
export const dogsReducer = createReducer(initialDogState,
on(DogAction.update,
((state: Dog[]), { dogs }) => {
return dogs;
}),
on(DogAction.add,
((state: Dog[]), { dog }) => {
return [...dogs, dog];
}),
);
And then register two features:
StoreModule.forFeature("cats", catsReducer),
StoreModule.forFeature("dogs", dogsReducer),
and to select
export const selectCats = createFeatureSelector('cats');
export const selectDogs = createFeatureSelector('dogs');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.