Tuesday, September 19, 2017

Angular: Share data between components using service file

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 how to make a component reusable and share 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'}
    ]
  }
}


<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.

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. 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. In this article we have discussed about sharing the data between components using a service file.

Related Post

1. Angular: Create reusable component and pass data to component.

2. Date filtering and formatting using pipe in Angular 2.

No comments :

Post a Comment