Federico Quaglia Federico Quaglia - 5 months ago 100
TypeScript Question

angular2 onclick call method service

I have a button component that has to call a function on event click:

<button pButton type="button" label="Add EchoBeacon" (click)="insertPoint()">
constructor(private mappaService: MappaService) {}
insertPoint() {
this.interaction = new ol.interaction.Draw({
type: /** @type {ol.geom.GeometryType} */ 'Point',
source: this.echoBeacons.getSource()
this.interaction.on('drawend', function(e) {
var feature = e.feature;
var geometry = feature.getGeometry();
this.coordinates = geometry.getCoordinates();
this.mappaService.savePoint(this.coordinates[0], this.coordinates[1])
data => console.log('Added'),
error => console.error('Error: ' + error),
() => console.log('Completed!')


and this is the method service :

savePoint(x: number, y :number): Observable<any[]>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let serverPostDbUrl ="";
let body = `{"x": ${x}, "y": ${y}}`;
return this.http.post(`${serverPostDbUrl}`, body, options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || "Server error"));


but when I click on button, console logs me that 'cannot read a property of undefined', like mappaService isn't defined in insertPoint() function


Your problem is with this line: this.interaction.on('drawend', function(e) {

Using regular functions definitions will change the context of this, so that it will no longer be the Component/Service. You will need to use Arrow Functions to maintain this.


this.interaction.on('drawend', (e) => {