Wednesday, September 20, 2017

Angular: How to communicate between a component and a service file

In this article we will be discussing about how to communicate between a component and a service file. If you are an angular 1 folk, don’t worry it is almost same except some syntax changes. In angular 1 it was controller to service/factory file here it is between a component and a service file. Let us check with one example.

Service file


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

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

Above one is the simple example of a service file, which has one method "setUserData()". Now let us check how we can inject this to a component and communicate each other.

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 {
  list:any;
  constructor(private _userData: userDataService){
    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 basically we have injected the dependency and you can easily set the values in the service file using "setUserData()" method.

Module code.


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

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

For accessing this to other component, just inject the service file and start using it. Component to component communication is possible without using a service file as well. You can refer below post for more info.

1. Share data between components using a service file.

2. Create reusable component and share data between them.

No comments :

Post a Comment