Communication pattern between parent and child using Subject services

Angular now a days they use Observable’s convention to Promises and callbacks. By using subject angular could store data dynamically during runtime. Subject is one type of observable that implement shared services to be communicated to any layer of components. To use this services we need to create injectable service using angular.

Consider we have two components the main component which is app.component.ts and another component which may be parent or child component subject-data.component.ts. Create a component using angular cli tools. Now our aim is to create a services and share between component. Create a service in angular using ng g s data here data is a service name. This will create a service class angular file data.service.ts and data.service.spec.ts. Right Now our focus is the service class file and not testing file. Consider the below service file data.service.ts

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

@Injectable()
export class DataService {
  private messageSource = new Subject<String>();
  constructor() { }
  public getMessage(): Observable<String> {
    return this.messageSource.asObservable();
  }
  public setMessage(mesg: String) {
    this.messageSource.next(mesg);
  }
}

In the above we created an instance of Subject which should be of type String. Now Create Two function getMessage() which should be returning of observable type. setMessage(msg) where msg should be passed as a string and using next method we pass what is the next data to be passed into the stream. As soon as set message is set here data get changed. In order to view the message the particular component should Inject the service in the constructor using Dependency Injection in angular.

If the particular service is injected in constructor. Then, we can use those methods in our components and call those methods. Consider the subject-data.component.ts below we have injected the service in constructor and call those methods and we indicated as subscribe as to get the data from the observable. Only when we subscribe data could be subscribed from the stream.

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-subject-data',
  templateUrl: './subject-data.component.html',
  styleUrls: ['./subject-data.component.css']
})
export class SubjectDataComponent implements OnInit {
  message: String;
  constructor(private data: DataService) { }

  ngOnInit() {
    console.log("Loading Subject data....");
      this.data.getMessage().subscribe(message => this.message = message);
      console.log(this.message);
  }

}

Consider subject-data.component.html here whenever data gets changed i.e message indicated will display the value

<p>
 {{message}}
</p>

Consider the app.component.html

<app-subject-data></app-subject-data>
<button (click)="updateSubject()">Update Subject</button>

In the above code we have subject component and button.

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'angular-data-sharing';
  constructor(private data: DataService) { }
  ngOnInit() {
    console.log("Loading App data....");
  }
  updateSubject() {
    this.data.setMessage(this.title);
  }
}

Whenever we Click the button, we set the value. As soon as we set value data is shared between all component to which it has been injected and a change has been reflected.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *

Comments (0)