Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to call a function from service in onclick event in angular 4

I have written a method getDataMethod() in the service 'data.service.ts'. I want to call this function when someone clicks on a submit button from the html page.

I have created an instance of the service in the constructor of the component, like below:

cnstructor(private dataservice: DataService){
    this.data-service-method = this.dataservice.getDataMethod();
}

How to call this function?

like image 540
sree Avatar asked Dec 24 '22 06:12

sree


2 Answers

You need to create an instance of the service inside the constructor of the component, then refer the service and call the method.

import { DataService } from './data.service';


export Class ComponentA { 
 constructor(public dataService: DataService) { } 
 myFunct(){
   this.dataService.getDataService().subscribe();
}
}
like image 67
Sajeetharan Avatar answered Apr 20 '23 01:04

Sajeetharan


You need to provide your service to a parent module or component itself (you can take one other approach in angular v6, take a look at official docs) and then inject it into your component, then you can use it on click or submit event.

Component(.ts) file:

export class TestComponent {
    constructor(public testService: TestService) {
    }
}

Template (.html) file:

<button (click)="testService.getDataService()">Button</button>

Although it's better if you call the service method from a method declared inside the component.

like image 42
Nima Hakimi Avatar answered Apr 20 '23 00:04

Nima Hakimi