Skip to main content

Create Angular Service to Communicate between Components

In previous articles we have seen how to communicate within components using @input and @output. Creating the Angular service to communicate with components are the best method compared to other. Angular service can be consumed by multiple components by subscribing to the service.
Here is the Example of Angular service:
In the below example I will be creating a service that will show the text entered in another component. From the below image,



  • Component 1 has a textbox
  • PreviewService is the service used to get the latest value in Component1 textbox.
  • Component 2 shows the value from PreviewService.
  • Component 3 shows the length of the value from PreviewService.
Preview-Service.Service.ts :
                       PreviewService is created with onUserEnters function that gets the input for the service and userTextObservable$ for exposing the same as a service. Here we have used BehaviouSubject that can hold the current value and previous value, where Subject can hold only current value.

import { Injectable } from '@angular/core';
import { BehaviorSubject } from '../../../node_modules/rxjs';

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

private _userTextSubject = new BehaviorSubject(null);
userTextObservable$ = this._userTextSubject.asObservable();

onUserEneters(userText :string){
  this._userTextSubject.next(userText);
}
constructor() { }
}


App.component.html : Here we are creating a textbox and two way binding for userText as shown below. It also holds the selector of the second and third component.

        


App.Component.ts:
            Here we use the service and call the onUserEnters function to keep PreviewService value UpToDate.

import { Component } from '@angular/core';
import {PreviewService} from '../app/services/preview-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private previewService: PreviewService){}
  
private _userText: string;
  get userText(){
  return this._userText;
}
  set userText(value :string){
    this._userText=value;
    this.previewService.onUserEneters(this._userText);
  }
}

Second-Component.Component.ts :
             Here we are consuming the service that created earlier and assigning the same to variable called previewText

import { Component, OnInit } from '@angular/core';
import {PreviewService} from '../services/preview-service.service';
@Component({
  selector: 'second-component',
  templateUrl: './second-component.component.html',
  styleUrls: ['./second-component.component.css']
})
export class SecondComponentComponent implements OnInit {

  public previewText:string;
  constructor(private previewService :PreviewService) { }

  ngOnInit() {
    this.previewService.userTextObservable$.subscribe(x=>this.previewText=x);
  }
}

Second-Component.Component.html :
              Here previewText is used to display the value.




Third-Component.Component.ts :
            Here we consume the service to get the value that entered in Component 1 and Assigning the length of the value to the charCount variable.

import { Component, OnInit } from '@angular/core';
import {PreviewService} from '../services/preview-service.service';
@Component({
  selector: 'third-component',
  templateUrl: './third-component.component.html',
  styleUrls: ['./third-component.component.css']
})
export class ThirdComponentComponent implements OnInit {

  public charCount:number=0;
  constructor(private previewService : PreviewService){}
  ngOnInit() {
    this.previewService.userTextObservable$.subscribe(
      x=>{
        if(x!=null)
            this.charCount=x.length;
      });
  }
}

Third-Component.Component.html :
           Displaying the charCount value to user



Include Forms Module and other components in app.module.ts


Thats it!!

Comments

  1. This was a wonderful site and I really enjoy it the data you shared. Cheers for sharing with us your wonderful blog.
    Break The Cup For boy Free game Gold Diggers Adventure play Rapunzel Fashionista Busy Day game

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. One of the defining traits of middle age is an acute and inescapable awareness of loss that seems to be wired into experience. Its autumnal tone is unexcitable and calm: it has lost the violent optimism of youth and is at peace with its fatalistic acceptance that life would not give another chance.Every evening is a dire reminder of another petal fallen off the dazzling, but wilting, flower of youth. Every morning, a tortured search in front of the mirror for another new grey, another line added to the deepening crow's feet.
    kizi kizi 2 games
    jogo friv gratis
    friv4school 2019

    ReplyDelete

Post a Comment