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?
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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With