Published: November 17 2022

Angular 14 - Communicating Between Components with RxJS Observable & Subject

Built with Angular 14.2.11 and RxJS 7.5.7

Other versions available:

This is a quick tutorial to show how you can send messages between components in an Angular 14 application with RxJS.

The way to communicate between components is to use an Observable and a Subject (which is a type of observable), I won't go too much into the details about how observables work here since it's a big subject, but in a nutshell there are two methods that we're interested in: Observable.subscribe() and Subject.next().

Observable.subscribe()

The observable subscribe method is used by angular components to subscribe to messages that are sent to an observable.

Subject.next()

The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers (a.k.a. observers) of that observable.


Angular 14 Component Communication Example

Here's a simple example that shows messages being sent from a home component to the root app component via a message service using RxJS Observables. Styling of the example is all done with Bootstrap 5.2 css.

(See on StackBlitz at https://stackblitz.com/edit/angular-14-communicating-between-components)


Angular 14 Message Service

The message service is implemented with an RxJS Subject<any> which is a subject that can send any type of argument to subscribers. The service exposes three methods:

  • sendMessage() is used to send the specified message string to all subscribers by calling this.subject.next({ text: message })
  • clearMessages() sends a null value to subscribers as a signal to clear all messages (see the app component below for how messages are cleared).
  • onMessage() is used to subscribe to new messages from any Angular component. It is exposed as an Observable while keeping the Subject private to encapsulate message sending within the message service. Essentially any component can read messages but on the service can write messages.
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessages() {
        this.subject.next(null);
    }

    onMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}


App Component that Receives Messages

The app component uses the message service to subscribe to new messages and push them into the local messages array prop which is rendered by the app component template.

When a null message is received, the component clears the messages array which removes them from the UI.

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { MessageService } from './_services';

@Component({ selector: 'app-root', templateUrl: 'app.component.html' })
export class AppComponent implements OnDestroy {
    messages: any[] = [];
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        // subscribe to home component messages
        this.subscription = this.messageService.onMessage().subscribe(message => {
            if (message) {
                this.messages.push(message);
            } else {
                // clear messages when empty message received
                this.messages = [];
            }
        });
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}


Home Component that Sends Messages

The home component contains methods that call the messageService to send and clear messages displayed by the app component.

import { Component } from '@angular/core';

import { MessageService } from '../_services';

@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {
    constructor(private messageService: MessageService) { }

    sendMessage(): void {
        // send message to subscribers via observable subject
        this.messageService.sendMessage('Message from Home Component to App Component!');
    }

    clearMessages(): void {
        // clear messages
        this.messageService.clearMessages();
    }
}

 


Need Some Angular 14 Help?

Search fiverr for freelance Angular 14 developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by