DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems
  • Faster Releases With DevOps: Java Microservices and Angular UI in CI/CD

Trending

  • Run Gemma 4 on Your Laptop: A Hands-On Guide to Google's Latest Open Multimodal LLM
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • Securing Everything: Mapping the Right Identity and Access Protocol (OIDC, OAuth2, and SAML) to the Right Identity
  • S3 Vectors: How to Build a RAG Without a Vector Database
  1. DZone
  2. Coding
  3. Frameworks
  4. Multicasting Observables Using RxJS Subjects in Angular

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.

By 
Sabya Sachi user avatar
Sabya Sachi
·
Updated May. 21, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
34.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

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

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

@Component({
  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 => {
        console.log(value);
        if (value.type === 'click') {
          console.log('input value: ', this.name);
          this.messageService.updateMessage(this.name);
        }
      });
  }
}

Let's see the HTML part of DataSendingComponent:

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

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';
@Component({
  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) {
    console.log(this.messagefromSibling);
    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.

AngularJS

Opinions expressed by DZone contributors are their own.

Related

  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems
  • Faster Releases With DevOps: Java Microservices and Angular UI in CI/CD

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook