December 01 2016

Angular 2/4 - Communicating Between Components with Observable & Subject

May 23 2017 - Updated to Angular 4.1.1

This is a quick post to show an example of something that got me stuck for a little while - how to communicate between components in Angular 2/4.

The solution 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, 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 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 subscribers of that observable.


Example of Component Communication in Angular 2/4

Here's a simple example showing a home component communicating with the root app component via a message service using observables.

The code is also available on GitHub at https://github.com/cornflourblue/angular2-communicating-between-components

(See on Plunker at http://plnkr.co/edit/FHIPt1?p=preview)

Update History:

  • 23 May 2017 - Updated to Angular 4.1.3
  • 01 Dec 2016 - Built with Angular 2.2.1


Running the Angular 2/4 Component Communication Example Locally

  1. Install NodeJS (> v4) and NPM (> v3) from https://nodejs.org/en/download/, you can check the versions you have installed by running node -v and npm -v from the command line.
     
  2. Download the project source code from https://github.com/cornflourblue/angular2-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 2/4 Message Service

The message service enables subscribing to messages and sending messages from any component in the application

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
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 2/4 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/Subscription';

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

@Component({
    moduleId: module.id,
    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 2/4 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({
    moduleId: module.id,
    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();
    }
}


Recommended Books on Angular 2/4


Web Development Sydney

Feel free to drop me a line if you're looking for an Angular 2/4 developer or web developer in Sydney Australia, I also provide remote contracting services for clients outside Sydney.


Sponsored by