Broadcasting with Subjects in angular 8

Posted By :Nikita Agarwal |30th November 2019

Subjects in angular:

Subjects are also observables but the difference between the two is that observable allows to subscribe only whereas subject allows to subscribe and publish.
SO by subject, we can use our service both as subscribers and publishers for data.
By this approach, we can do inter components interaction i.e to transfer data between components.

By use of subject, we can access the values where we subscribe to that subject.
This makes it very easy to access data over components.

Here is a sample example for using subjects:

1.First create an angular project.


2.In app.component.html file replace with
  
<div *ngIf="message">
  {{message}}
</div>
<app-home>
</app-home>

3.Make a home.component with angular cli.

4.Replace the content with:

<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>

here #message is a local template variable which we have to declare in our ts file

5.Add a property
message: string; 

6.Now  generate a service file via cli  i.e example.service.ts
Now import the Subject Observable into the service file.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class ExampleService {
  public message = new Subject<string>();
  setMessage(value: string) {
    this.message.next(value); 
   //it is publishing this value to all the subscribers that have already subscribed to this message
  }
}

7.Now inject this example service instance in your App.component.ts file where you want to access the value of "message".
8.Like


import { Component } from '@angular/core';
import { ExampleService } from '../../service/example.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  constructor(public example:ExampleService) { }
  setMessage(event) {
    console.log(event.value);
    this.example.setMessage(event.value);
  }
}

9.Now  in the same component subscribe and unsubscribe the message service data.
Like:

export class AppComponent {
  message: string;
  subscription: Subscription;
  constructor(public example: ExampleService) { }
  ngOnInit() {
    this.subscription = this.example.message.subscribe(
      (message) => {
        this.message = message;
      }
    );
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}


Now, here in this example shown :

any value entered inside #message of home.component.html shall be printed to {{message}}inside app.component.html.
 

Reference:

https://angular.io/


About Author

Nikita Agarwal

Nikita Agarwal is a front-end developer and have a good knowledge of HTML , CSS ,Javascipt and Bootstrap and Angular

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us