Search code examples
angularangular2-services

Receive service data on button click in Angular 2


I'm working on the services in angular 2. I need to call the service on button click. I was able to access on constructor of the component. I kenw that the constructor executes as soon as the component created. But the same thing which i done in my constructor I was not able to access on button click. I need to set the service return string value to the property. Below was my code..

import { Component } from '@angular/core';
import {MyFirstServiceClass} from './FirstService.service'
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  svcdata : string;
  constructor(private  servtest : MyFirstServiceClass )
  {    
      this.svcdata =  servtest.SayHelloToService();
  }
  ServiceOnButtonClick(){
    // How to access here  servtest.SayHelloToService(); I tried But not 
     //able to access
  }
}

My Template Code :

<div style="text-align:center">
  Show service data : {{svcdata}} <br/>
  <button id='btn' (click)='ServiceOnButtonClick()'>Click Me ! </button>
</div>

My service Code :

import {Injectable} from '@angular/core'
@Injectable()
export class MyFirstServiceClass{
  SayHelloToService(){      
      return 'Hello, welcome your service...';
  }
}

Solution

  • Just call it inside the method ServiceOnButtonClick using this

    constructor(private  servtest : MyFirstServiceClass )
    {    
    
    }
    ServiceOnButtonClick(){
        this.svcdata =  this.servtest.SayHelloToService();
    }