How to communicate between angular components through a shared service?

In the previous post I showed how to interact between angular components using @Input and @Output annotations.

A parent component can pass data to child component using @Input annotation.

A child component can emit an event (with data if required) to parent using @Output annotation

The link is here :

How do components communicate in Angular ? – Part I

In this post I will explain how to communicate between components using services.

Let’s say a parent component wants to pass a message to a child component . Just ask “Hey Child how are you ?”

Let’s create a service for this using Observable pattern:

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

@Injectable({
  providedIn: 'root'
})
export class MessageService{

  constructor() { }


   messageSubject = new Subject<string>();


  sayMessage(message:string){

    this.messageSubject.next(message);
  }

}

Here ‘messageSubject’ is a Subject which publishes string values when they are passed through sayMessage() method to whoever has subscribed to it.

Lets create a parent component which pushes message to this subject on click of a button:

The typescript component code:

import { Component, OnInit } from '@angular/core';
import { Service1Service } from '../service1.service';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  providers: [MessageService],
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  constructor(private service:MessageService) { }

  ngOnInit() {
  }


  messageChild(){

    this.service.sayMessage("Hey Child how are you");


  }

}

Notice that the service is included in the providers declaration . This limits the scope of the service to the parent component and its children.

The template :



<button (click)="messageChild()">Message Child</button>

<app-child></app-child>

On click of the button “Message Child” the parent passes the message “Hey Child how are you?” to the MessageService.

This service then pushes the message to the Subject “messageSubject”.

The child component subscribes to this subject as shown in the below code and as soon as the subject publishes this message , it receives it:

import { Component, OnInit } from '@angular/core';
import { Service1Service } from '../service1.service';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor(private service:MessageService) {
    
   }

  ngOnInit() {

    this.service.messageSubject.subscribe(
{
      next: x => alert(x)

}
    );

      
  }

}

Now on click of the button in parent component , the alert “Hey Child how are you?” is displayed:

I have included nothing in the child component template for simplicity.

That’s it!


Posted

in

,

by

Comments

3 responses to “How to communicate between angular components through a shared service?”

  1. Tyson Avatar

    Thanks for postinng this

    1. Vijay SRJ Avatar
      Vijay SRJ

      You are welcome

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading