1. Introduction to State Management
State management is a critical aspect of building scalable applications. In Angular, managing shared and component-specific states can quickly become complex as the application grows. State management helps maintain a single source of truth for the application state and improves consistency and debugging capabilities.
2. Services vs. Store (NgRx)
Using Services for State Management
Angular services are a simple and effective way to manage state for smaller applications. Services can store state and share it across components:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StateService {
private state = { count: 0 };
getState() {
return this.state;
}
updateState(newState: Partial) {
this.state = { ...this.state, ...newState };
}
}
Using NgRx Store for State Management
For larger applications, a more robust solution like NgRx is recommended. NgRx follows the Redux pattern, providing a centralized state with actions, reducers, and selectors for managing and accessing state.
3. Using NgRx for State Management
NgRx is a state management library for Angular. It uses RxJS to handle state as a stream of immutable updates. NgRx revolves around three main concepts: Actions, Reducers, and Selectors.
4. Actions, Reducers, and Selectors
Actions
Actions represent events that trigger state changes. They are defined as simple objects with a type and optional payload:
import { createAction, props } from '@ngrx/store';
export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const setCounter = createAction('[Counter] Set', props<{ value: number }>());
Reducers
Reducers are pure functions that specify how the state changes in response to actions.
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, setCounter } from './counter.actions';
export const initialState = 0;
const _counterReducer = createReducer(
initialState,
on(increment, (state) => state + 1),
on(decrement, (state) => state - 1),
on(setCounter, (state, { value }) => value)
);
export function counterReducer(state: any, action: any) {
return _counterReducer(state, action);
}
Selectors
Selectors are functions that extract specific slices of state. They improve code modularity and reusability.
import { createSelector } from '@ngrx/store';
export const selectCounter = (state: any) => state.counter;
export const selectCounterValue = createSelector(
selectCounter,
(counter) => counter
);
5. Setting Up NgRx
To use NgRx in your Angular application, install the necessary packages:
npm install @ngrx/store @ngrx/effects @ngrx/entity @ngrx/store-devtools
Then, register the store module in your app:
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { counterReducer } from './state/counter.reducer';
@NgModule({
imports: [
StoreModule.forRoot({ counter: counterReducer })
]
})
export class AppModule { }
0 Comments