# What is a BehaviorSubject in Angular ?

In 
Published 2022-12-03

This tutorial explains to you what a BehaviorSubject is in Angular and also provide you with an example.

In Angular, in many cases we need to see the value(s) of a stream in real time and in the same time we need to get access to this stream to many consumers (subscribers). Each subscriber/ consumer will do different things function on the stream value(s). In this situation we have to define a Subject or a BehaviorSubject.

A BehaviorSubject = a set/ stream of data a subscriber (consumer) can subscribe to.

The subscriber can see the NEW data in the stream and also the initial or the LAST value in the stream. If you don't want to see the last value of the stream you have to use Subject in Angular. It might be useful for you to take a look at the following articles as well: ReplaySubject in Angular and AsyncSubject in Angular.

In order to use this feature, you have to import "BehaviorSubject" from 'rxjs' or 'rxjs/BehaviorSubject' into the component that use it:

import { BehaviorSubject } from 'rxjs';

Here is the code we used for showing BehaviorSubject behavior in Angular 4:

import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
 
  products = [
    {name:"apples", price:10, onStock:"Y"},
    {name:"bananas", price:5, onStock:"Y"},
    {name:"tomatoes", price:11, onStock:"Y"}
  ];
 
  ngOnInit() {
 
    console.log('BehaviorSubject:');
    let subject3 = new BehaviorSubject<number>(0);
 
    let subscription31 = subject3.subscribe( var1  => {
      console.log('subscription31 /'+var1+'/');
    });
    console.log('-----------------------------------');
    subject3.next(1);
    console.log('CurrentValue='+subject3.getValue());
    console.log('-----------------------------------');
    let subscription32 = subject3.subscribe( var2  => {
       console.log('subscription32 /'+var2+'/');
    });
    subject3.next(2);
    console.log('===================================');
 }
}

And here is the result in the browser console: