June 25 2018

Angular 6 - Communicating Between Components with Observable & Subject

Built with Angular 6.0.6

This is a quick tutorial to show how you can communicate between components in Angular 6 and TypeScript. The tutorial example uses Webpack 4 for compiling + bundling and is styled with bootstrap 4.

For a previous version built with Angular 5 check out Angular 2/5 - Communicating Between Components.

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 6 Component Communication Tutorial Example

Here's a simple example showing communication between the home component and the root app component via a message service using observables.

The tutorial code is available on GitHub at https://github.com/cornflourblue/angular-6-communicating-between-components

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


Running the Angular 6 Component Communication Example Locally

  1. Install NodeJS and NPM from https://nodejs.org/en/download/.
  2. Download or clone the tutorial project code from https://github.com/cornflourblue/angular-6-communicating-between-components
  3. Install all required npm packages by running npm install from the command line in the project root folder (where the package.json is located).
  4. Start the application by running npm start from the command line in the project root folder.


Angular 6 Message Service

With the message service you can subscribe to new messages in any component, and send messages from any component in the application.

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 });
    }

    clearMessage() {
        this.subject.next();
    }

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


Angular 6 App Component that Receives Messages

The app component uses the message service to subscribe to new messages and make them available to the app component template via the message property.

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

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

@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})

export class AppComponent implements OnDestroy {
    message: any;
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        // subscribe to home component messages
        this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
    }

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


Angular 6 Home Component that Sends Messages

The home component uses the message service to send messages to the app component.

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

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

@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!');
    }

    clearMessage(): void {
        // clear message
        this.messageService.clearMessage();
    }
}


Web Development Sydney

Feel free to contact me if you're looking for an Angular 6 developer in Sydney, I also provide remote contracting services for clients outside Sydney.


Sponsored by