Angular 14 Advanced State Management using ngrx with Employee Example

State management is a critical aspect of any modern web application. In Angular, there are several ways to manage state, including using a service or a simple store. However, for large and complex applications, it can be challenging to manage state in a centralized and efficient manner. That’s where ngrx comes in.

ngrx is a library that implements the Redux pattern in Angular. It allows for centralized state management, predictable state updates, and powerful debugging tools. In this tutorial, we’ll learn how to use ngrx to manage state in an Angular application by building an example application that manages a list of employees.

 

Step 1: Installation

To get started, we’ll need to install the ngrx packages. Run the following command in your terminal:

npm install @ngrx/store @ngrx/effects @ngrx/store-devtools --save

 

Step 2: Create the Store

In ngrx, the store is the central repository of the application’s state. It’s where we’ll keep all the data that our application needs to function.

First, we’ll create an interface for our state. In our example application, we’ll have a list of employees, so we’ll create an interface called AppState that has a property called employees of type Employee[].

interface AppState {
  employees: Employee[];
}

 

Next, we’ll create a reducer function that will handle the state updates. The reducer function takes the current state and an action and returns the next state. In our example, we’ll have two actions: one for adding an employee and one for removing an employee.

import { createReducer, on } from '@ngrx/store';
import { addEmployee, removeEmployee } from './employee.actions';

export const initialState: AppState = {
  employees: []
};

export const employeeReducer = createReducer(
  initialState,
  on(addEmployee, (state, { employee }) => {
    return { ...state, employees: [...state.employees, employee] };
  }),
  on(removeEmployee, (state, { id }) => {
    return { ...state, employees: state.employees.filter(e => e.id !== id) };
  })
);

Finally, we’ll create the store using the StoreModule from the @ngrx/store package and configure it with our reducer and initial state.

import { StoreModule } from '@ngrx/store';
import { employeeReducer } from './employee.reducer';

@NgModule({
  imports: [
    StoreModule.forRoot({ employees: employeeReducer }, { initialState })
  ]
})
export class AppModule {}

 

Step 3: Create the Effects

Effects in ngrx are a way to handle side effects, such as API calls, in a centralized and predictable way. In our example, we’ll create an effect that will handle adding an employee to the API.

First, we’ll import the necessary modules from the @ngrx/effects package.

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';

 

Next, we’ll create an effect that listens for the addEmployee action, makes an API call to add the employee, and dispatches the addEmployeeSuccess action on success. In case of an error, it will dispatch an action to handle the error.

@Injectable()
export class EmployeeEffects {
  addEmployee$ = createEffect(() =>
    this.actions$.pipe(
      ofType('[Employee] Add Employee'),
      switchMap(({ employee }) => {
        return this.employeeService.addEmployee(employee).pipe(
          map((employee: Employee) => {
            return { type: '[Employee API] Add Employee Success', employee };
          }),
          catchError((error: any) => {
            return of({ type: '[Employee API] Add Employee Failure', error });
          })
        );
      })
    )
  );

  constructor(private actions$: Actions, private employeeService: EmployeeService) {}
}

 

Finally, we’ll add the effects to the @ngrx/effects module and configure them in our app’s module.

import { EffectsModule } from '@ngrx/effects';
import { EmployeeEffects } from './employee.effects';

@NgModule({
  imports: [
    EffectsModule.forFeature([EmployeeEffects])
  ]
})
export class AppModule {}

And that’s it! We’ve set up advanced state management using ngrx in our Angular application. With this setup, we can easily manage the state of our employee list and handle any side effects in a centralized and predictable way.

 

Conclusion

In conclusion, ngrx is a powerful library that allows for advanced state management in Angular applications. It uses the Redux pattern and provides a centralized store, predictable state updates, and powerful debugging tools. In this tutorial, we’ve built an example application that manages a list of employees using ngrx. We’ve covered how to create the store, reducers, and effects, and how to configure them in our Angular application. By following these steps, you can easily set up ngrx in your own Angular application and take advantage of its powerful features for managing state.

Leave a Comment

Your email address will not be published. Required fields are marked *