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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  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.

Sabya Sachi user avatar by
Sabya Sachi
·
May. 21, 19 · Tutorial
Like (3)
Save
Tweet
Share
30.93K 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.

Popular on DZone

  • Visual Network Mapping Your K8s Clusters To Assess Performance
  • Do Not Forget About Testing!
  • DevSecOps Benefits and Challenges
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: