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
Newsletter
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

  • Every Generation Fears the Machine. Here Is How the AI Job Panic Usually Ends
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • When a Coding Agent Fixes the Test Instead of the Bug
  • RAG Architecture Patterns: Proxy, Caching, and Routing

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Updated May. 21, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
34.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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