loading...
Cover image for Subject - RxJS in Angular

Subject - RxJS in Angular

muhammadawaisshaikh profile image Muhammad Awais ・1 min read

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers.

While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast. A Subject is like an Observable, but can multicast to many Observers.

Real Scenario,

Let's Suppose, We have a component that is showing updated messages, and this component is reusable and used in 3 to 4 parent components, and we want to make this in a way that it will get synced to everywhere to show updated messages as soon as it received. so in these type of situations Subject - RxJS comes in where syncing involved.

Create a new service:

// message-service.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  public message = new Subject<string>();

  constructor() { }

  setMessage(value) {
    this.message.next(value);
  }
}

1 of the Parent component, where the above service is used, so every time a new message is entered, all the parent components who subscribed this service will get the updated message in all parent components:

<!-- home.component.html -->

<input type="text" name="message" id="message">
<input type="button" value="Send" (click)="setMessage()">
// home.component.ts

import { MessageService } from 'services/message-service.service';

constructor(
    private messageService: MessageServiceService
  ) { }

ngOnInit() {
    this.getUpdatedMessage();
  }

getUpdatedMessage() {
    this.messageService.message.subscribe(
      res => {
        console.log('message', res);
      }
    )
  }

setMessage() {
    let message = (<HTMLInputElement>document.getElementById("message")).value;
    this.messageService.setMessage(message);
  }

That's All Folks ;)

Posted on by:

muhammadawaisshaikh profile

Muhammad Awais

@muhammadawaisshaikh

ReactJS | Angular | JavaScript | NodeJS| Ruby on Rails | Heroku | AWS

Discussion

pic
Editor guide