In Angular, a BehaviorSubject is a part of RxJS (Reactive Extensions for JavaScript) and is used to store and emit the most recent value to its subscribers. It’s a subclass of the RxJS Subject
, which is a special kind of Observable that allows values to be multicasted to many observers.
Key Concepts of BehaviorSubject
in Angular:
Initial Value: A BehaviorSubject
It requires an initial value when it’s created, which is immediately emitted to any subscribers.
Latest Value: It always holds the latest value. Any new subscriber will automatically receive the last emitted value.
Multiple Subscribers: Just like a Subject
, multiple subscribers can subscribe to the BehaviorSubject
, and they will all receive the same latest value when it is updated.
State Management: BehaviorSubject
is often used in Angular services for managing state or data streams across components. It allows one or more components to react to data changes simultaneously.
Key Methods:
next(value)
: Updates the current value of the BehaviorSubject
and emits it to all subscribers.
subscribe()
: Subscribes to the BehaviorSubject
, receiving the current value and any updates.
getValue()
: Allows access to the current value without subscribing.
Difference between Subject vs Behavior Subject
1) Behavior Subject is used to initialize the value while Subject you can not initialize the value.
const behaviorSubject = new BehaviorSubject(2);
Note:- You can initialize any value like string/ number/boolean
const subject = new Subject();
Note:- You can not initialize value.
2) Subject has upcoming value while Behavior Subject has previous and upcoming value.
There are many steps to define the difference between Subject and Behavior Subject
Step A) Suppose, you call the Subject and Behavior Subject Object value into the component comp1 then value John is showing into the Behavior Subject.
Step B) When you fill the employee value Tom into the textbox and click on the submit button then value will be show into the Subject and Behavior Subject.
Step C) Now, you click on the About Us page menu then call the about-us component and show the value of this component.
Step D) Now, you back to the Home page menu then Subject does not have value while Behavior Subject has previous value Tom.
Example:- Define the Subject and Behavior Subject through the code.
There are some steps to define the Subject and Behavior Subject code.
Step1) Firstly create the main.service.ts file and import the BehaviorSubject, Subject from the rxjs library and create the object of the Subject and BehaviorSubject and initialize the value John into the BehaviorSubject.
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MainService {
constructor() { }
employeeNameBySubject = new Subject();
employeeNameByBehaviorSubject = new BehaviorSubject('John');
}
Step2) Now, create the component comp1 and we import the main.service.ts file into the comp1.component.ts file and inject the MainService into the constructor function and call the subscribe method of the class’s subject variable employeeNameBySubject and Behavior Subject variable employeeNameByBehaviorSubject.
import { Component, OnInit } from '@angular/core';
import { MainService } from '../main.service';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.scss']
})
export class Comp1Component implements OnInit {
employeeNameBySubject: string = '';
employeeNameByBehaviorSubject: string = '';
constructor(private _mainService : MainService) {
this._mainService.employeeNameBySubject.subscribe(ename=>{
this.employeeNameBySubject = ename;
});
this._mainService.employeeNameByBehaviorSubject.subscribe(enamebybs=>{
this.employeeNameByBehaviorSubject = enamebybs;
})
}
ngOnInit(): void {
}
updateEmpName(empName: { value: string; }){
this._mainService.employeeNameBySubject.next(empName.value);
this._mainService.employeeNameByBehaviorSubject.next(empName.value);
}
}
Step3) Now, put the below code into the comp1.component.html file.
<div align="center" class="container">
<div class="row align-items-center justify-content-center template-container">
<div style="height: 10px"></div>
<div class="row">
<div class="col-md-6"> <h3>Subject</h3>
<h4>Emp Name - {{ employeeNameBySubject }}</h4>
</div>
<div class="col-md-6"> <h3>Behavior Subject</h3>
<h4>Emp Name - {{ employeeNameByBehaviorSubject }}</h4>
</div>
</div>
<div class="row"><b>Employee Name </b>
<input type="textbox" name="empName" #empName />
</div>
<div style="height: 10px"></div>
<div class="row">
<input class="btn btn-primary" type="button" (click)="updateEmpName(empName)" value="submit"/>
</div>
<div style="height: 10px"></div>
</div>
</div>
Note:- call the employeeNameBySubject and employeeNameByBehaviorSubject variable into the textbox, We defined the template reference variable “empName” and pass into the updateEmpName() function as a parameter.