The behaviorSubject class is a part of rxjs library, with the help BeviorSubject we can share data between two components and handle data streams that need to hold and emit the most recent value to subscribers. It’s mostly used in such scenarios as sharing state between components, communication between services, and managing asynchronous data updates.

Here’s how can you use BehaviorSubject in your Angular application:

Step – 1 Import the required modules:

Import the BehaviorSubject class from the RxJS library in your Angular Service, Here I have created a data service and set up my BehaviorSubject Property

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private userDataSubject = new BehaviorSubject<any>(initialValue);
  public userDataObserable = this.userDataSubject.asObservable()

  constructor() { }


  setUserData(userInfo){
    this.userDataSubject.next(userInfo);
  }
}
data.service.ts – TypeScript

Step – 2 Subscribe to the BehaviorSubject

You can subscribe to BehaviorSubject Observable to receive updated data whenever the value changes. Make sure to unsubscribe from the Observable to avoid memory leaks.

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private _dataService: DataService) {}
  ngOnInit(): void {
    this._dataService.userDataObserable.subscribe(userData => {
      // Here you will get updated userInformation
      console.log(userData)
    })
  }
  onSetUserData(){
    const user = {
      userID: '1234',
      userName: 'Aditya Mishra',
      designation: 'Senior Software Engineer'
    }
    this._dataService.setUserData(user);
  }
  ngOnDestroy() {
    this._dataService.userDataSubject.unsubscribe();
  }
}
app.component.ts – TypeScript

Note: that retains the last emitted value, so new subscribers will immediately receive the latest value when they subscribe.

Also, keep in mind…

that while BehaviourSubject is a powerful tool, improper use can lead to complex data flows and potential issues. It’s important to carefully design and manage your data streams to ensure a maintainable and predictable application.

OpenLayers Setup in Angular App | Step By Step

Comments to: How to use BehaviorSubject in Angular

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

    Attach images - Only PNG, JPG, JPEG and GIF are supported.