DEV Community

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

Posted on

3 1

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

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

  public message = new Subject<string>();

  constructor() { }

  setMessage(value) {
    this.message.next(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';

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);
  }
Enter fullscreen mode Exit fullscreen mode

That's All Folks ;)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

nextjs tutorial video

📺 Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay