State Management in Angular Using Rxjs

Introduction

In Angular, state management is managing application state and data in a predictable and efficient manner. RxJS is a powerful library that can manage state in Angular applications.

How to Manage State in Angular using RxJS?

1. Create a new Angular service to manage the state. In this example, we'll call it "StateService".

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StateService {
  private _count = new BehaviorSubject<number>(0);

  get count$() {
    return this._count.asObservable();
  }

  increment() {
    this._count.next(this._count.value + 1);
  }

  decrement() {
    this._count.next(this._count.value - 1);
  }
}

2. In this service, we're using a BehaviorSubject to manage the state of a count variable. We're also exposing an observable count$ that other components can subscribe to receive updates when the count changes. Finally, we've defined two methods to increment and decrement the count.

3. Now, we can use this service in our Angular components. For example, let's create a simple counter component:

import { Component } from '@angular/core';
import { StateService } from './state.service';

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="increment()">+</button>
    {{ count | async }}
    <button (click)="decrement()">-</button>
  `
})
export class CounterComponent {
  count = this.stateService.count$;

  constructor(private stateService: StateService) {}

  increment() {
    this.stateService.increment();
  }

  decrement() {
    this.stateService.decrement();
  }
}

4. In this component, we inject the StateService and subscribe to the count$ observable using the async pipe. We're also defining two methods to increment and decrease the count by calling the StateService methods.

5. Finally, we can add this component to our main app component:

import { Component } from '@angular/core';
import { CounterComponent } from './counter.component';

@Component({
  selector: 'app-root',
  template: `
    <h1>Counter App</h1>
    <app-counter></app-counter>
  `
})
export class AppComponent {}

6. When we run the app, we can see that the counter updates in real-time as we click the buttons.

Summary

This is just a simple example, but you can use RxJS and Angular services to manage more complex states in your applications.


Similar Articles