How to communicate between a component and a service file

In this article, we discuss How to communicate between a component and a service file

How to communicate between a component and a service file

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

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.

We are coming to the end of the article. I hope to understand How to communicate between a component and a service file.

Source: Various

Also Checkout Sharing Data between Components using Service in Angular

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

Related Posts

One thought on “How to communicate between a component and a service file

Leave a Reply

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