Implementing NgRx step by step in an Angular app ??
Muhammad Awais
Software/Ai Technologist ?? | Internationally Recognised Lead Software Engineer | Speaker | Author x2 | Mentor | OpenSource Contributor
Angular app involves setting up the NgRx store, actions, reducers, effects, and integrating them into your components. NgRx is a state management library that helps you manage complex application states with predictable patterns. Here's a comprehensive step-by-step guide:
Step 1: Set Up Your Angular Application: Ensure you have Angular CLI installed. If not, install it using:
npm install -g @angular/cli
Step 2: Create a New Angular Project: Create a new Angular project using the Angular CLI:
ng new ngrx-app
Step 3: Install NgRx Packages: Install the NgRx packages for the store, effects, and devtools:
cd ngrx-app npm install @ngrx/store @ngrx/effects @ngrx/store-devtools
Step 4: Create directory nesting this way for Scalable approach:
Step 5: Set Up Actions: Create action files in your application to define the actions that will be dispatched to the store. For example, create a counter.actions.ts file:
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter Component] Increment');
export const decrement = createAction('[Counter Component] Decrement');
export const reset = createAction('[Counter Component] Reset');
Step 6: Define the State: Create a file named counter.state.ts to define the initial state of your application:
export interface CounterState {
count: number;
}
export const initialCounterState: CounterState = {
count: 0
};
Step 7: Set Up Reducers: Create reducer files to define how the state changes in response to dispatched actions. For example, create a counter.reducer.ts file:
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
import { initialCounterState } from './counter.state';
export const counterReducer = createReducer(
initialCounterState,
on(increment, state => ({ ...state, count: state.count + 1 })),
on(decrement, state => ({ ...state, count: state.count - 1 })),
on(reset, state => initialCounterState)
);
Step 8: Implement Effects: Create an effects file to handle asynchronous actions or side effects. For example, create a counter.effects.ts file:
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { increment, decrement, reset } from './counter.actions';
import { tap } from 'rxjs/operators';
@Injectable()
export class CounterEffects {
increment$ = createEffect(() =>
this.actions$.pipe(
ofType(increment),
tap(() => console.log('Increment effect triggered'))
),
{ dispatch: false }
);
constructor(private actions$: Actions) {}
}
Step 9: Configure the Store: In your app.module.ts file, import necessary NgRx modules and configure the store:
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { counterReducer } from './counter.reducer';
import { CounterEffects } from './counter.effects';
@NgModule({
declarations: [...],
imports: [
// ...
StoreModule.forRoot({ counter: counterReducer }),
EffectsModule.forRoot([CounterEffects])
],
// ...
})
export class AppModule { }
Step 10: Integrate with Components: Use the NgRx store in your components by dispatching actions and selecting state. For example, in your counter.component.ts:
领英推荐
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
@Component({
selector: 'app-counter',
template: `
<div>
<button (click)="increment()">Increment</button>
<div>Count: {{ count }}</div>
<button (click)="decrement()">Decrement</button>
<button (click)="reset()">Reset</button>
</div>
`
})
export class CounterComponent {
count: number;
constructor(private store: Store<{ counter: CounterState }>) {
this.store.select('counter').subscribe(state => {
this.count = state.count;
});
}
increment() {
this.store.dispatch(increment());
}
decrement() {
this.store.dispatch(decrement());
}
reset() {
this.store.dispatch(reset());
}
}
Step 10: View the NgRx DevTools: Open your application in the browser and install the NgRx DevTools extension. This tool provides a visual representation of your store, actions, and state changes.
Congratulations ?? ! You've implemented NgRx step by step in your Angular app. You've set up actions, reducers, effects, and integrated them into your components, creating a predictable and manageable state management solution.
SSE | ? Angular, ?? ReactJS, ?? JavaScript, ?? TypeScript, ?? | Crafting Visually Stunning, High-Performing, and Accessible Web Solutions
1 年thanks for sharing