Subject And Behavior Subject In Angular 8

Introduction

 
In this article, we are going to see Subject and Behavior Subject in RxJs library.
 

What is a Subject?

 
Subject is a special type of Observable in RxJs Library in which we can send our data to other components or services. A Subject is like an Observable but can multicast to many observers which means subject is at the same time an Observable and an Observer.
 
Here are some important points of subjects
  • A Subject is a Special type of Observable that allows value to be multicasted to many Observers.
  • Subject are like event emitters.
  • No Initial Value
  1. subject =new Subject<datatype>();  

What is a Behavior Subject?

 
Behavior Subject is similar to subject but only difference is that we can set the initial value .
 
A variant of subject that requires initial value.
  1. const subject =new BehaviorSubject(0); //0 is the initial value.   

Difference between Subject and Behavior Subject?

 
In Subject we cannot set an initial value but in Behavior subject we have to set an initial value otherwise it will throw an error. 
 
Prerequisites
  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed
Step 1
 
Create a new Angular project using the following NPM command:
  1. ng new subjectExample
Step 2
 
Let's create 3 Components that will communicate the data with each other components using the following NPM command,
  1. ng g c Component1  
  2. ng g c Component2  
  3. ng g c Component3  
Step 3
 
Now in the app.component.html file lets import the components selector using the following command.
  1. <div style="text-align: center;  
  2. font-size: x-large;  
  3. font-family: monospace;">Example of Subject in RxJs</div>  
  4. <div style="margin:10px" class="card-deck">  
  5.   <app-component1></app-component1>  
  6.   <app-component2></app-component2>  
  7.   <app-component3></app-component3>  
  8. </div>  
Step 4
 
After than open Component1.component.html file and paste the below code.
  1. <div style="background-color: aliceblue;" class="card">  
  2.   <div class="card-body">  
  3.     <h5 class="card-title">Component 1</h5>  
  4.     <input name="comp1" #comp1 type="text" />  
  5.     <button (click)="onSubmit(comp1)">Submit</button>  
  6.     <p class="card-text">{{Component1Data}}</p>  
  7.   </div>  
  8. </div>  
Step 5
 
Now Open Component1.component.tsfile and paste the below code.
  1. import { Component } from '@angular/core';  
  2. import { DataSharingService } from '../data-sharing.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-component1',  
  6.   templateUrl: './component1.component.html',  
  7.   styleUrls: ['./component1.component.css']  
  8. })  
  9. export class Component1Component {  
  10.   
  11.   Component1Data: any = '';  
  12.   
  13.   constructor(private DataSharing: DataSharingService) {  
  14.     this.DataSharing.SharingData.subscribe((res: any) => {  
  15.       this.Component1Data = res;  
  16.     })  
  17.   }  
  18.   
  19.   onSubmit(data) {  
  20.     this.DataSharing.SharingData.next(data.value);  
  21.   }  
  22. }  
 
In the above image SharingData is sending data using next as well as subsribed in the constructor to fetch the data in the data stream.
 
Step 6
 
Like the above, open Component2.component.html and paste in that file.
  1. <div style="background-color:antiquewhite" class="card">  
  2.   <div class="card-body">  
  3.     <h5 class="card-title">Component 2</h5>  
  4.     <input name="comp2" #comp2 type="text" />  
  5.     <button (click)="onSubmit(comp2)">Submit</button>  
  6.     <p class="card-text">{{Component2Data}}</p>  
  7.   </div>  
  8. </div>  
Step 7
 
Open Component2.component.ts and paste the below code.
  1. import { Component } from '@angular/core';  
  2. import { DataSharingService } from '../data-sharing.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-component2',  
  6.   templateUrl: './component2.component.html',  
  7.   styleUrls: ['./component2.component.css']  
  8. })  
  9. export class Component2Component {  
  10.   Component2Data: any = '';  
  11.   
  12.   
  13.   constructor(private DataSharing: DataSharingService) {  
  14.     this.DataSharing.SharingData.subscribe((res: any) => {  
  15.       this.Component2Data = res;  
  16.     })  
  17.   }  
  18.   
  19.   onSubmit(data) {  
  20.     this.DataSharing.SharingData.next(data.value);  
  21.   }  
  22. }  
Step 8
 
Paste the below code in our 3rd component which is Component2.component.html.
  1. <div style="background-color:burlywood" class="card">  
  2.   <div class="card-body">  
  3.     <h5 class="card-title">Component 3</h5>  
  4.     <input name="comp3" #comp3 type="text" />  
  5.     <button (click)="onSubmit(comp3)">Submit</button>  
  6.     <p class="card-text">{{Component3Data}}</p>  
  7.   </div>  
  8. </div>  
Step 9
 
Now Paste the below code in our 3rd component which is Component2.component.ts.
  1. import { Component } from '@angular/core';  
  2. import { DataSharingService } from '../data-sharing.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-component3',  
  6.   templateUrl: './component3.component.html',  
  7.   styleUrls: ['./component3.component.css']  
  8. })  
  9. export class Component3Component {  
  10.   
  11.   Component3Data: any = '';  
  12.   
  13.   constructor(private DataSharing: DataSharingService) {  
  14.     this.DataSharing.SharingData.subscribe((res: any) => {  
  15.       this.Component3Data = res;  
  16.     })  
  17.   }  
  18.   
  19.   onSubmit(data) {  
  20.     this.DataSharing.SharingData.next(data.value);  
  21.   }  
  22.   
  23. }  
Step 10
 
Now it's time to create a common service so that one service can transfer the data and use the stream of data.
 
 dataService.service.ts
  1. import { Injectable } from '@angular/core';  
  2. import { Subject } from 'rxjs';  
  3.   
  4. @Injectable({  
  5.   providedIn: 'root'  
  6. })  
  7. export class DataSharingService {  
  8.   
  9.   SharingData = new Subject();  
  10.   constructor() { }  
  11. }  
Now it's time to see the output,
 
In this example there are 3 components which do not have a parent child relationship,  but we are sending data from one component to Component2 and Component3 using rxjs subject.
 

Conclusion

 
In this article we have seen the special library of rxjs.
 
I hope you have enjoyed this article as much as I have enjoyed writing and coding the examples.
 
Please let me know in the comments how I could improve it and any suggestions from your end.