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

  4. Thanks for your extraordinary blog. Your idea for this was so brilliant. This would provide people with an excellent tally resource from someone who has experienced such issues. You would be coming at the subject from a different angle and people would appreciate your honesty and frankness. Good luck for your next blog!
    Tally ERP 9 Training
    tally classes
    Tally Training institute in Chennai
    Tally course in Chennai
    seo training classes
    seo training course
    seo training institute in chennai
    seo training institutes
    seo courses in chennai
    seo institutes in chennai
    seo classes in chennai
    seo training center in chennai

    ReplyDelete
  5. Thanks for your extraordinary blog. Your idea for this was so brilliant. This would provide people with an excellent tally resource from someone who has experienced such issues.

    Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now

    more details click the link now

    https://www.webdschool.com/web-development-course-in-chennai.html

    ReplyDelete
  6. Thanks for sharing this valuable information to our vision. You have posted a worthy blog keep sharing.
    Digital Marketing Course In Kolkata
    Web Design Course In Kolkata
    SEO Course In Kolkata

    ReplyDelete

Post a Comment