Using subject in Service to communicate between component

  • Subject is a special type of Observable
  • A Subject is a observer as well as observer.
  • As subject involves taking a notification from a single source and forwarding them to one or more destinations.
  • And this subject is usually placed in a service so if there are 5 component subscribed to this subject then all receives this message

interaction.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class InteractionService {
  private _teacherMessageSource = new Subject<String>();
  teacherMessageSource$ = this._teacherMessageSource.asObservable();
  constructor() { }

  sendMessgae(message: string){
    this._teacherMessageSource.next(message);
  }
}

app.component.html

<h1>Teacher</h1>
<button (click)="greetStudent()">Greet Student</button>
<button (click)="appreciateStudent()">Apprceate Student</button>
<app-child></app-child>

app.component.ts

import { InteractionService } from './interaction.service';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'SubjectAsService';

  constructor(private _interationService: InteractionService) {}

  greetStudent(){
    this._interationService.sendMessgae('Good Morning');
  }
  appreciateStudent(){
    this._interationService.sendMessgae('Well Done');
  }
}

child.component.html

<h2>Student</h2>

child.component.ts

import { InteractionService } from './../interaction.service';
import { Component, OnInit } from '@angular/core';

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

  constructor(private _interactionService: InteractionService) { }

  ngOnInit() {
    this._interactionService.teacherMessageSource$
    .subscribe(
    (message) => {
      if(message === 'Good Morning'){
        alert('Good Morning teacher');
      } else if(message === 'Well Done'){
        alert('Thank you teacher');
      }
    }
    );
  }
}

Leave a Comment