Angular course Β· Module 10: State Management
Classic NgRx Store
In this lesson3
NgRx Store is the Redux pattern for Angular - powerful, but more complex.
NgRx Structure
store/
βββ samurai.actions.ts # Actions
βββ samurai.reducer.ts # Reducer
βββ samurai.selectors.ts # Selectors
βββ samurai.effects.ts # Effects (side effects)
βββ samurai.state.ts # State interfaceActions
import { createAction, props } from '@ngrx/store';
// Loading
export const loadSamurai = createAction('[Samurai] Load');
export const loadSamuraiSuccess = createAction(
'[Samurai] Load Success',
props<{ samurai: Samurai[] }>()
);
export const loadSamuraiFailure = createAction(
'[Samurai] Load Failure',
props<{ error: string }>()
);
// CRUD
export const addSamurai = createAction(
'[Samurai] Add',
props<{ samurai: Samurai }>()
);
export const deleteSamurai = createAction(
'[Samurai] Delete',
props<{ id: number }>()
);Reducer
import { createReducer, on } from '@ngrx/store';
export interface SamuraiState {
samurai: Samurai[];
loading: boolean;
error: string | null;
}
const initialState: SamuraiState = {
samurai: [],
loading: false,
error: null
};
export const samuraiReducer = createReducer(
initialState,
on(loadSamurai, (state) => ({
...state,
loading: true,
error: null
})),
on(loadSamuraiSuccess, (state, { samurai }) => ({
...state,
samurai,
loading: false
})),
on(loadSamuraiFailure, (state, { error }) => ({
...state,
loading: false,
error
})),
on(addSamurai, (state, { samurai }) => ({
...state,
samurai: [...state.samurai, samurai]
})),
on(deleteSamurai, (state, { id }) => ({
...state,
samurai: state.samurai.filter(s => s.id !== id)
}))
);Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does an Action represent in NgRx?
2. What does a Reducer do in NgRx when it receives an action?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the actions and reducer for managing samurai in NgRx.
- Horizontal ordering
Arrange the createAction call with the action type and props (one line, left to right):
- Vertical ordering
Order the actions describing the data loading flow in NgRx (from start to finish):
- Vertical ordering
Order the one-way flow in classic NgRx (from event to view):