Cross Component Communication using Subjects in Angular

Rashmi Bang
3 min readSep 23, 2020

--

An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. Subjects are like EventEmitters: they maintain a registry of many listeners. There are two things when we talk about Subjects or any observables in general:

  • The sender
  • And the receiver

In the case of Subjects, the one calling the ‘next’ method is the sender and the one calling the subscribe method is the receiver. Subscribe does not invoke a new execution that delivers values, it simply registers the given Observer in a list of Observers, to fetch the asynchronous data. So whenever someone calls the next method, the callback in subscribe method is invoked.

There are three types of subjects:

  1. Subject — the default one (and the scope of this article)
  2. BehaviorSubject — which always has value
  3. ReplaySubject — which maintains a record of past values

Here we will discuss a chat application:

There are two components, the message sender and the receivers (or receivers in case of group chat).

To communicate between two components, we need:

  1. A shared service that can be injected in both the components
  2. Calling the subscribe method in the receiver
  3. Calling the next method in the sender

Step One: Creating a shared service

Here’s the shared service with two subjects. One for sending the message from FirstComponent to SecondComponent and the other one for the reverse.

@Injectable({
providedIn: 'root'
})
export class DataserviceService {
messageFirst = new Subject();
messageecond = new Subject();

constructor() {
}
}

Inject the shared service to the FirstComponent and SecondComponent using dependency injection like this:

import {DataserviceService} from ‘../dataservice.service’;
export class FirstComponent implements OnInit {
constructor(private service: DataserviceService) {}
}

Similarly, inject in SecondComponent.

Step Two: Calling the next method to send the data

Now on the click of button we need to get the recent message, create a send method that gets called and it then triggers the next method on the subject:

FirstComponent:
send(message: string): void {
this.service.messagefirst.next(message);
}

And similarly while sending from SecondComponent to FirstComponent:

SecondComponent:
send(message: string): void {
this.service.messagesecond.next(message);
}

Step Three: Subscribing to the subjects to receive the data

Last, but not least, we need to subscribe to the subjects:

FirstComponent:

ngOnInit(): void {
this.service.messageFirst.subscribe((param: string) => {
// do something with the received message});
}

And similarly to receive in second component:

ngOnInit(): void {
this.service.messageSecond.subscribe((param: string) => {
// do something with the received message});
}

Step Four: Sending more than just a string

Next method supports sending only object — be it a string, number, array or any Javascript object. If you have multiple values we can create an interface and pass that to the next method.

interface Message {
text: string;
time: Date;
Sender: string;
Receiver: string;
}

Summary

Cross component communication can be achieved using a shared service and subject. To do so you need:

  1. A shared service among both the sender and receiver
  2. Next method call in sender
  3. Subscribe method call in receiver.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rashmi Bang
Rashmi Bang

No responses yet

Write a response