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
- 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.
- const subject =new BehaviorSubject(0);
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:
Step 2
Let's create 3 Components that will communicate the data with each other components using the following NPM command,
- ng g c Component1
- ng g c Component2
- ng g c Component3
Step 3
Now in the app.component.html file lets import the components selector using the following command.
- <div style="text-align: center;
- font-size: x-large;
- font-family: monospace;">Example of Subject in RxJs</div>
- <div style="margin:10px" class="card-deck">
- <app-component1></app-component1>
- <app-component2></app-component2>
- <app-component3></app-component3>
- </div>
Step 4
After than open Component1.component.html file and paste the below code.
- <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>
Step 5
Now Open Component1.component.tsfile and paste the below code.
- import { Component } from '@angular/core';
- import { DataSharingService } from '../data-sharing.service';
-
- @Component({
- selector: 'app-component1',
- templateUrl: './component1.component.html',
- styleUrls: ['./component1.component.css']
- })
- export class Component1Component {
-
- Component1Data: any = '';
-
- constructor(private DataSharing: DataSharingService) {
- this.DataSharing.SharingData.subscribe((res: any) => {
- this.Component1Data = res;
- })
- }
-
- onSubmit(data) {
- this.DataSharing.SharingData.next(data.value);
- }
- }
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.
- <div style="background-color:antiquewhite" 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>
Step 7
Open Component2.component.ts and paste the below code.
- import { Component } from '@angular/core';
- import { DataSharingService } from '../data-sharing.service';
-
- @Component({
- selector: 'app-component2',
- templateUrl: './component2.component.html',
- styleUrls: ['./component2.component.css']
- })
- export class Component2Component {
- Component2Data: any = '';
-
-
- constructor(private DataSharing: DataSharingService) {
- this.DataSharing.SharingData.subscribe((res: any) => {
- this.Component2Data = res;
- })
- }
-
- onSubmit(data) {
- this.DataSharing.SharingData.next(data.value);
- }
- }
Step 8
Paste the below code in our 3rd component which is Component2.component.html.
- <div style="background-color:burlywood" 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>
Step 9
Now Paste the below code in our 3rd component which is Component2.component.ts.
- import { Component } from '@angular/core';
- import { DataSharingService } from '../data-sharing.service';
-
- @Component({
- selector: 'app-component3',
- templateUrl: './component3.component.html',
- styleUrls: ['./component3.component.css']
- })
- export class Component3Component {
-
- Component3Data: any = '';
-
- constructor(private DataSharing: DataSharingService) {
- this.DataSharing.SharingData.subscribe((res: any) => {
- this.Component3Data = res;
- })
- }
-
- onSubmit(data) {
- this.DataSharing.SharingData.next(data.value);
- }
-
- }
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
- import { Injectable } from '@angular/core';
- import { Subject } from 'rxjs';
-
- @Injectable({
- providedIn: 'root'
- })
- export class DataSharingService {
-
- SharingData = new Subject();
- constructor() { }
- }
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.