What Is Subject And Behavior Subject In Angular 13

In this, article we are going to learn about what is Subject and Behavior Subject, the Difference between both of them, and small examples.

What is a Subject?

The subject is a special type of Observable in the RxJs Library with the help of that we can send our data to other components or services. A Subject is like an Observable but it is multicast to many observers which means the subject is at the same time an Observable and an Observer.

Syntax:

subject = new Subject();

What is a Behavior Subject?

Behavior Subject is similar to a subject but the only difference is that we can set the initial value.

Syntax:

const subject = new BehaviorSubject(0); //0 is the initial value.

Subject Vs Behaviour Subject

1. A Subject is used to immediately notify subscribers of updated values emitted by it. It does not keep track of old values, i.e. if a Subject observable first emitted a value and then later subscribed it, then the subscriber will not get that value.

1. A BehaviorSubject behaves like a Subject but it has an extra feature, i.e. it preserves the last emitted value. That means if a value was emitted earlier and if a subscription was added after the value was emitted, then the subscription will give the last value that was emitted.

2. We can’t set the initial value in Subject.

2. We have to set the initial value in Behavior Subject otherwise it will throw an error.

Let us understand with help of one example.

Prerequisites

  • Basic knowledge of Angular.
  • Visual Studio Code must be installed.
  • Angular CLI must be installed.
  • Node JS must be installed.

First, create a new project with help of the following command.

ng new subject-behaviorsubject-Example

Open the style.css and paste the below line in it for bootstrap design.

@import '~bootstrap/dist/css/bootstrap.min.css';

Let’s create 3 components. 

ng g c Component1  
ng g c Component2  
ng g c Component3

Now open app.component.html and paste the below code in it.

<div class="row mt-5">
    <div class="col-md-4">
        <app-component1></app-component1>
    </div>
    <div class="col-md-4">
        <app-component2></app-component2>
    </div>
    <div class="col-md-4">
        <app-component3></app-component3>
    </div>
</div>

Now create dataService.ts with the help of the following command.

ng g service dataService

Open dataService.ts and paste the below code into it

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

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
  SharingData = new Subject();//subject
   constructor() { }

 //update value
  changeDataSubject(data: any) {
    this.SharingData.next(data.value);
  }
}

Open component1.ts and paste the below code in it.

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

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {
  Component1Data: any = '';
  constructor(private DataSharing: DataServiceService) {
    DataSharing.SharingData.subscribe((res: any) => {
      this.Component1Data = res;
    })
  }

  ngOnInit(): void {
  }
  onSubmit(data: any) {
    this.DataSharing.changeDataSubject(data);
  }
}

Open component1.html and paste the below code in it.

<div style="background-color: aliceblue;" class="card">
    <div class="card-body">
        <h5 class="card-title">Component 1</h5>
        <input name="comp1" #comp1 type="text" />
        <button (click)="onSubmit(comp1)">Submit</button>
        <p class="card-text">{{Component1Data}}</p>
    </div>
</div>

Open component2.ts and paste the below code in it.

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

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
  Component2Data: any = '';
  constructor(private DataSharing: DataServiceService) {
    DataSharing.SharingData.subscribe((res: any) => {  
      this.Component2Data = res;
    })
  }

  ngOnInit(): void {
  }
  onSubmit(data: any) {
    this.DataSharing.changeDataSubject(data);
  }
}

Open component2.html and paste the below code in it.

<div style="background-color: aliceblue;" class="card">
    <div class="card-body">
        <h5 class="card-title">Component 2</h5>
        <input name="comp2" #comp2 type="text" />
        <button (click)="onSubmit(comp2)">Submit</button>
        <p class="card-text">{{Component2Data}}</p>
    </div>
</div>

Open component3.ts and paste the below code in it.

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

@Component({
  selector: 'app-component3',
  templateUrl: './component3.component.html',
  styleUrls: ['./component3.component.css']
})
export class Component3Component implements OnInit {
  Component3Data: any = '';
  constructor(private DataSharing: DataServiceService) {
    DataSharing.SharingData.subscribe((res: any) => {
      debugger
      this.Component3Data = res;
    })
  }

  ngOnInit(): void {
  }
  onSubmit(data: any) {
    this.DataSharing.changeDataSubject(data);
  }
}

Open component3.html and paste the below code in it.

<div style="background-color: aliceblue;" class="card">
    <div class="card-body">
        <h5 class="card-title">Component 3</h5>
        <input name="comp3" #comp3 type="text" />
        <button (click)="onSubmit(comp3)">Submit</button>
        <p class="card-text">{{Component3Data}}</p>
    </div>
</div>

That’s it.
Run the project with help of the following command.

ng serve

Output:

While using Behaviour Subject we can set the default value as given below.

Open data-services.ts and modify code as given below.

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

@Injectable({
  providedIn: 'root'
})
export class DataServiceService {
 // SharingData = new Subject();
 SharingData = new BehaviorSubject('default');
 constructor() { }

  changeDataSubject(data: any) {
    this.SharingData.next(data.value);
  }
}

Rest code is will be as it is.

As you can see above image default value is set with help of BehaviorSubject.

Also, check to Call Multiple API Using CombineLatest In Angular 13.

2 Comments

  1. Swapnil Dasharath Kadu

    Great Article

    0
    0
    Reply
    1. Thanks, Swapnil.

      0
      0
      Reply

Submit a Comment

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

Subscribe

Select Categories