Sunday 7 May 2023

State management in Angular using NgRx

NgRx is a state management library for Angular that provides a predictable state container for managing application state. It can be used to manage shared state between the client and server-side of an Angular application, including when using an Angular Universal application with a .NET Core REST API.


Here's an example of how NgRx can be used with a .NET Core REST API:


Install NgRx - First, install NgRx by running the following command in the Angular application directory:

npm install @ngrx/store --save
Define a state - Define the application state in the AppState interface. For example:
export interface AppState {
  todos: Todo[];
}

Define actions - Define actions that describe the state changes that can occur in the application. For example:

  

export enum TodoActionTypes {
  ADD_TODO = '[Todo] Add Todo',
  REMOVE_TODO = '[Todo] Remove Todo',
}

export class AddTodo implements Action {
  readonly type = TodoActionTypes.ADD_TODO;

  constructor(public payload: { todo: Todo }) {}
}

export class RemoveTodo implements Action {
  readonly type = TodoActionTypes.REMOVE_TODO;

  constructor(public payload: { id: number }) {}
}

export type TodoActions = AddTodo | RemoveTodo;

Define reducers - Define reducers that handle the state changes described by the actions. For example:

 

export function todoReducer(state: Todo[] = [], action: TodoActions) {
  switch (action.type) {
    case TodoActionTypes.ADD_TODO:
      return [...state, action.payload.todo];
    case TodoActionTypes.REMOVE_TODO:
      return state.filter((todo) => todo.id !== action.payload.id);
    default:
      return state;
  }
}

Define selectors - Define selectors that provide access to specific parts of the application state. For example:

export const selectTodos = (state: AppState) => state.todos;

Dispatch actions - In the Angular application, dispatch actions to update the application state. For example:

 

constructor(private store: Store) {}

addTodo() {
  const todo = { id: 1, title: 'Buy milk', completed: false };
  this.store.dispatch(new AddTodo({ todo }));
}

removeTodo() {
  const id = 1;
  this.store.dispatch(new RemoveTodo({ id }));
}
appstate

Use the state in the .NET Core REST API - In the .NET Core REST API, use the state provided by NgRx to generate the API response. For example:

 

[HttpGet] public ActionResult>; GetTodos()
{
  var todos = _store.Select(state => state.todos);
  return Ok(todos);
}

By using NgRx with a .NET Core REST API, developers can manage shared state between the client and server-side of an Angular application, enabling server-side rendering and improving performance and user experience.

No comments:

Post a Comment