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';  

export class userDataService {  
       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.


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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  constructor(private _userData: userDataService){
    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';

  declarations: [
  imports: [
  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