Thursday, 14 January 2021

Subject with Example | Angular2+

 What is a Subject?

Subject is a type of Observable in RxJs Library in which we can send our data to other components or services.

While Observables are unicast by design. Subjects can multicast. Multicasting basically means that one Observable execution is shared among multiple subscribers.

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. Understanding of Subject

Important points of subjects:

  1. A Subject is a Special type of Observable that allows value to be multicasted to many Observers.
  2. Subject are like event emitters.
  3. No Initial Value allowed

subject =new Subject<datatype>();  

Lets create a basic demo for subject.

1- Create an angular application using below command: ng new subjectDemo   

2- Add three components in app/src using below command: 

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

3- After that 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> 

4- After that open Component1.component.ts file and paste the below code.

import { Component } from '@angular/core';
import { DataSharingService } from '../dataService.service';

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.scss']
})
export class Component1Component{

  Component1Dataany = '';  
  
  constructor(private DataSharingDataSharingService) {  
    this.DataSharing.SharingData.subscribe((resany=> {  
      this.Component1Data = res;  
    })  
  }  
  
  onSubmit(data: { valueany; }) {  
    this.DataSharing.SharingData.next(data.value);  
  }  
}

5- After that open Component2.component.html file and paste the below code.

<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> 

6- After that open Component2.component.ts file and paste the below code.

import { Component } from '@angular/core';
import { DataSharingService } from '../dataService.service';

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.scss']
})
export class Component2Component{

  Component2Dataany = '';  
  constructor(private DataSharingDataSharingService) {  
    this.DataSharing.SharingData.subscribe((resany=> {  
      this.Component2Data = res;  
    })  
  }  
  
  onSubmit(data: { valueany; }) {  
    this.DataSharing.SharingData.next(data.value);  
  }  
}

7- After that open Component3.component.html file and paste the below code.

<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>

8- After that open Component3.component.ts file and paste the below code.

import { ComponentOnInit } from '@angular/core';
import { DataSharingService } from '../dataService.service';

@Component({
  selector: 'app-component3',
  templateUrl: './component3.component.html',
  styleUrls: ['./component3.component.scss']
})
export class Component3Component {
  Component3Dataany = '';  
  
  constructor(private DataSharingDataSharingService) {  
    this.DataSharing.SharingData.subscribe((resany=> {  
      this.Component3Data = res;  
    })
  }

  onSubmit(data: { valueany; }) {  
    this.DataSharing.SharingData.next(data.value);  
  } 
}

9- 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> 

10- Now let's create a service so that one service can transfer data and use the stream of data.

import { Injectable } from '@angular/core';  
import { Subject } from 'rxjs';  
  
@Injectable({  
  providedIn: 'root'  
})  
export class DataSharingService {  
  
  SharingData = new Subject();  
  constructor() { }  
}

11- Now Run the application using ng serve command.


Change data in one component and submit. You will see the output in all component. 


Related Posts:

  • CORS in Express CORS in Express using TypeScript A quick walkthrough on configuring CORS in your Express app using TypeScript and the cors middleware. Cross-origin… Read More
  • Angular Code Questions Q: How to get data from url in Angular  http://localhost:4200/about/7 const routes: Routes = [    { … Read More
  • Transclusion using ng-content Understanding Transclusion Transclusion means the inclusion of the content of one document in another document. Content Projection in Angular wit… Read More
  • RXJS Operators Operators By Category 1- Creating Observables Operators that originate new Observables. Create — create an Observable from scratch by calling… Read More
  • Difference Among Angular 8, 7, 6, 5, 4, 3, 2Difference Among Angular 8, 7, 6, 5, 4, 3, 2 — Breakdown, New Features, and ChangesThe first version of Angular was released in the year of 2010. Some… Read More

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives