Data state management in angular 2/4/6/8/9/10/11/12/13 using RxJs BehaviourSubject

Data state management in angular 2

Hello developers, As we know as angular developers sometimes we are required to maintain global data, and it's a different task to handle and manage it

We have an external library or state management framework to use as available options like NgRx, NgRx most popular state manager library with angular, and it's widely used but without NgRx we can achieve state management functionality in angular using RxJs BehaviourSubject

So step by step I will explain how we can do state management in angular2+ or the latest version of Angular

Finally, I added GitHub link of this demo angular state management project

Pre Request for start with angular:

  • You should have already installed the latest and stable version of node js.
  • You should have already installed the latest version of angular.

Let's start to manage state management in angular: 

Step 1) Create an angular project using a terminal using the command 

ng new ngStateManagerapp -- routing=true

  • here ngStateManagerapp is an angular app name you can whatever you want 
  • --routing=true flag add routing module during project creation

The angular project will be created in your destination folder

Step 2) Navigate inside the project root folder using the same terminal by typing

cd ngStateManagerapp 




Step 3) Create a few Angular Components (pages) using terminal

create angular component

ng g c home
ng g c about 
ng g c contact

Finally, create a service file 

ng g s state // it will create state.service.ts

Step 4) open project in visual studio code (vs code) editor

Step 5) Update the state.service.ts file

state.service.ts file

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
class LocalState {
  public counter: number;
  constructor() {
    this.counter = 0;
  }
}

@Injectable({
  providedIn: 'root'
})
export class StateService {
  public localStateData: LocalState = new LocalState();
  public localState = new BehaviorSubject<any>(this.localStateData); // Handle Local storage

  constructor() {
    if (localStorage.hasOwnProperty('localState')) {
      let localStorageData: any = localStorage.getItem('localState');
      this.localState.next(JSON.parse(localStorageData));
    }
    this.localState.subscribe((updatedData: any) => {
      this.localStateData = updatedData;
      localStorage.setItem('localState', JSON.stringify(this.localStateData));
    })

  }

  public updatedData(data: any) {
    this.localState.next(data);
    sessionStorage.setItem('localState', JSON.stringify(data))
  }

}

Step 6) Update the app.routing.module.ts file as below

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'home', pathMatch: 'full'
  },
  {
    path: "home",
    component: HomeComponent
  },
  {
    path: "about",
    component: AboutComponent
  },
  {
    path: "contact",
    component: ContactComponent
  },
  {
    path: "**",
    redirectTo: "home",
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { useHash: true }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule { }



Step 7) Update app.component.html

<div>
  <a routerLink="/home"> Home </a>
  <a routerLink="/about"> about </a>
  <a routerLink="/contact"> contact </a>
</div>
<router-outlet></router-outlet>

Step 8) Update home.component.html

<p>Home</p>
<div>
    <span>Counter value: {{stateService.localStateData.counter}} </span>
    <button (click)="increaseCounter()">Increase Counter</button>
    <button (click)="clearCounter()">Clear Counter</button>
</div>

Step 9) Update home.component.ts

home.component.ts screen

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(public stateService: StateService) { }

  public increaseCounter(){
    this.stateService.localStateData.counter++
    // this.stateService.updatedData(this.stateService.localStateData);
    this.stateService.localState.next(this.stateService.localStateData);
  }

  public clearCounter(){
    this.stateService.localStateData.counter = 0;
    this.stateService.localState.next(this.stateService.localStateData);
  }

  ngOnInit(): void {
  }

}


Step 10) Same home component changes do in about and contact component

Step 11) Run your project with angular command ng serve 

Test by using all three home, about, and contact pages you will counter increase button increase counter by clicking on the button and navigate your pages you will find count no will not loss so data state is managing
We can test it by page reloading it will not change till we clear the counter











Post a Comment

0 Comments