DEV Community

Cover image for Subject - RxJS in Angular
Muhammad Awais
Muhammad Awais

Posted on

Subject - RxJS in Angular

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

  providedIn: 'root'
export class MessageService {

  public message = new Subject<string>();

  constructor() { }

  setMessage(value) {;
Enter fullscreen mode Exit fullscreen mode

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()">
Enter fullscreen mode Exit fullscreen mode
// home.component.ts

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

    private messageService: MessageServiceService
  ) { }

ngOnInit() {

getUpdatedMessage() {
      res => {
        console.log('message', res);

setMessage() {
    let message = (<HTMLInputElement>document.getElementById("message")).value;
Enter fullscreen mode Exit fullscreen mode

That's All Folks ;)

Top comments (0)