Multicasting Observables Using RxJS Subjects in Angular

DZone 's Guide to

Multicasting Observables Using RxJS Subjects in Angular

We take a look at how to make two components in an Angular application talk to each other using RxJS.

· Web Dev Zone ·
Free Resource

Today, Reactive Programming is the most discussed topic in many JavaScript frameworks or libraries, like Angular, React, etc. Let's talk about one of the important aspects of Reactive Extensions called Subjects.

First, let's go by the definition given by the RxJS official docs.

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.

There are a few flavors to the Subjects, like BehaviorSubject, ReplaySubject, and AsyncSubject. To find out the difference between those subjects, I would recommend you to visit this link.

Let's say that we have two independent components that want to talk to each other. Here, let's say we don't have any parent-child relationships between them.

So, we prefer Subjects over such scenarios irrespective of the nested levels of the components, as we can share the data between those components.

Pertaining to the topic, we will share the data using the Service and whichever components are emitting the value to the service; the other components will be receiving the value from the service that has subscribed to it.

Let's create a simple Message service as follows:

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

export class MessageService {
myMessage = new Subject<string>();
  constructor() { }
  getMessage(): Observable<string> {
    return this.myMessage.asObservable();
  updateMessage(message: string) {

Now, if we observe there are two methods, called getMessage() and updateMessage(), which signifies that one component will send the message to the service which in turn will send the message to the other component which has sibscribed to the subject.

Now, let's create the other component, called DataSendingComponent, as follows:

import { Component } from '@angular/core';
import { MessageService } from './message.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

  selector: 'data-send',
  templateUrl: './data-send.component.html',
  styleUrls: ['./data-send.component.css']
export class DataSendingComponent {
  name = 'Angular';
  constructor(private messageService: MessageService) { }
  ngOnInit() { }
  passInputData() {
    var button = document.querySelector('button');
    var keyups = Observable.fromEvent(button, 'click')
      .subscribe(value => {
        if (value.type === 'click') {
          console.log('input value: ', this.name);

Let's see the HTML part of DataSendingComponent:

<h1>Multicasting observbles using Rxjs Subjects</h1>
<input type="text" [(ngModel)]="name" />
  <button id="btnClick" (click)="passInputData()">Click Me</button>

Now, let's see the other part of it which is the DataReceivingComponent:

import { Component, Input } from '@angular/core';
import { MessageService } from './message.service';
import { Subscription } from 'rxjs';
  selector: 'data-receving',
  template: `<h1>Hello!</h1> {{ messagefromSibling }}`,
  styles: [`h1 { font-family: Lato; }`]
export class DataRecevingComponent {
  @Input() name: string;
  subscription: Subscription;
  messagefromSibling: string;

  constructor(private messageService: MessageService) {
    this.subscription = this.messageService.getMessage()
      .subscribe(mymessage => {
        console.log('Getting value from Data Sending component: ', mymessage);
        this.messagefromSibling = mymessage

If you see now, the DataReceivingComponent is getting a value from the DataSendingComponent whenever the user clicks the button. To make this topic a bit simpler and more straight-forward, I am sending the data whenever the user clicks the button and, in turn, it's emitting the data out from the component.

Finally, the output will be shown as:

Angular Application Output

Angular Application Output

In such scenarios, it makes sense to use Subjects over the typical way of using @Output, @Input, and @ViewChild when you have scenarios like independent components.

I hope, you liked this article, and happy reading and coding!

If you enjoyed this post you might want to follow me on Twitter for more news around JavaScript, RxJS, and Angular.

angular tutorial, rxjs with angular 5, web application data, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}