Sharing Data between Components using Service in Angular

In this article, we discuss Sharing Data between Components using Service in Angular

Sharing Data between Components using Service in Angular

Sharing Data between Components using Service in Angular
Sharing Data between Components using Service in Angular

We can easily communicate with components by making a service file common. Inject the service file where ever you want and use it and this is the most preferred way. In the previous article I have explained about making a component reusable and sharing data between them. Now let us check by using a service file. Let us create two components first.

First Component

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title:String;
  list:any;
  constructor(){
    this.title = "Angular: Share data using service ";
    this.list = [
      {name:'Prashobh',age:'25'},
      {name:'Abraham',age:'35'},
      {name:'Anil',age:'40'},
      {name:'Sam',age:'40'},
      {name:'Philip',age:'40'},
      {name:'Bal',age:'40'},
      {name:'Anu',age:'20'}
    ]
  }
}

Sharing Data between Components using Service in Angular

HTML

<div>
  <h3> {{title}}</h3>
  <app-list></app-list>
</div>

Second component

import { Component,Input } from '@angular/core';

@Component({
  selector: 'app-list',
  template:'<div>' 
    +'<button (click)="fetchDataFromService()">Get User Data</button>'
    +'<ul class="list" *ngIf="showList">'
     +'<li *ngFor="let l of list">{{l.name}}</li>'
    +'</ul>'
    +'</div>',
  styleUrls: ['./app.component.css']
})
export class Applist {
  list : any[];
  showList : boolean;
  constructor(){
    this.showList = false;
  }
  fetchDataFromService(){
     this.showList = true;
   }
}

We have created two basic component and output will looks like below image.

sharedatausingservice
Sharing Data between Components using Service in Angular

There is a list array in the first component, we are going to set that array into our service file and that can be used by any other component. Let us check how we can achieve that.

Service file

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

@Injectable()
export class userDataService {  
   list:any;
   getUserData(){ 
      return this.list; 
   } 
   setUserData(data:any[]){
       this.list = data;
   }
}

Here we have two methods setUserData and getUserData. Using setUserData method we can set the data and that can be used anywhere by using getUserData method. You can use service file for making an API calls as well. I have written about the same using http and httpClient. httpClient is supported by Angular 4.3 version onwards. Now let us check below updated components to get more idea.

Updated First Component

import { Component } from '@angular/core';
import {userDataService} from './userDataService'; 

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title:String;
  list:any;
  constructor(private _userData: userDataService){
    this.title = "Angular: Share data using service ";
    this.list = [
      {name:'Prashobh',age:'25'},
      {name:'Abraham',age:'35'},
      {name:'Anil',age:'40'},
      {name:'Sam',age:'40'},
      {name:'Philip',age:'40'},
      {name:'Bal',age:'40'},
      {name:'Anu',age:'20'}
    ]
    this._userData.setUserData(this.list);
   }
   
}

Here we are setting the data to our userDataService.

Updated Second component

import { Component,Input } from '@angular/core';
import {userDataService} from './userDataService'; 

@Component({
  selector: 'app-list',
  template:'<div>' 
    +'<button (click)="fetchDataFromService()">Get User Data</button>'
    +'<ul class="list" *ngIf="showList">'
      +'<li *ngFor="let l of list">{{l.name}}</li>'
    +'</ul>'
    +'</div>',
  styleUrls: ['./app.component.css']
})
export class Applist {
  list : any[];
  showList : boolean;
  constructor(private _userData: userDataService){
    this.showList = false;
  }
  fetchDataFromService(){
     this.showList = true;
     this.list = this._userData.getUserData();
   }
}

Sharing main module code as well below for better understanding.

Module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { DatePipe } from '@angular/common';
import { AppComponent } from './app.component';
import { Applist } from './app.listComponent';
import {userDataService} from './userDataService';

@NgModule({
  declarations: [
    AppComponent,Applist
  ],
  imports: [
    BrowserModule,
  ],
  providers: [userDataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

We are done, click on the fetchDataFromService button and you can see the list. Here I have used angular (click) and *ngIf.

We are coming to the end of the article. I hope to understand sharing the data between components using a service file.

Source : Various

Also Checkout How to communicate between a component and a service file

If you interested in the Entertainment genre please check this also thebiographys.com

Related Posts

One thought on “Sharing Data between Components using Service in Angular

Leave a Reply

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