Invoke method from service on click in Angular 2

I'm facing an issue with a button component that should trigger a function on click event:

<button pButton type="button" label="Add EchoBeacon" (click)="insertPoint()">
 constructor(private mappaService: MappaService) {}
...
insertPoint() {
    this.map.removeInteraction(this.interaction);
    this.select.getFeatures().clear();
    this.map.removeInteraction(this.select);
    this.interaction = new ol.interaction.Draw({
      type: /** @type {ol.geom.GeometryType} */ 'Point',
      source: this.echoBeacons.getSource()
    });
    this.map.addInteraction(this.interaction);
    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])
         .subscribe(
            data => console.log('Added'),
            error => console.error('Error: ' + error),
            () => console.log('Completed!')
         );

}

Here's the method service being used:

savePoint(x: number, y :number): Observable<any[]>{
  let headers      = new Headers({ 'Content-Type': 'application/json' });
  let options       = new RequestOptions({ headers: headers });
  let serverPostDbUrl ="http://172.16.32.1:3000/beacon";
  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"));

}

However, upon clicking the button, I receive an error in the console stating 'cannot read a property of undefined', indicating that mappaService is not defined within the insertPoint() function.

Answer №1

The issue lies in the following line of code:

this.interaction.on('drawend', function(e) {

When using regular function definitions, the context of 'this' changes and it no longer refers to the Component/Service. To solve this, Arrow Functions need to be used in order to maintain the correct context for 'this'.

For example:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Code containing insertAdjacentHTML() does not run as expected due to injection of script

I have a scenario in my application where I am sending a request from the client to a node.js server. The server responds with an HTML containing a script: app.post('/verify', cors(issue2options), async (req, res) => { let auth = await mon ...

Unique loading of images without duplication

Hello everyone! I came across a script that loads images sequentially into my div element. It's working well, but I'd like to make it load random images without repeating any until all have been shown. As a newbie in this area, I've made so ...

Is it possible to control Firestore's data using an Angular service?

I am currently developing a basic example (Tour of Heroes) in Angular.io utilizing Firestore. In order to enhance readability and organization, the sections related to Firestore were segregated within the service and then referred in each component. Howev ...

The MaxDuration feature for a 5-minute time limit is malfunctioning on the Serverless Pro Plan, resulting in a 504 ERROR on

I am currently using Next.js@latest with App Directory My application is hosted on Vercel I'm experiencing a 504 error from Vercel and I'm on the pro plan. My serverless functions are set to run for up to 5 minutes, but usually, they only take ...

Is there a way to create submit buttons that trigger printing in HTML? Additionally, how can I design a text input that spans 100% width on the same line as a <span>, <p>, or <div>?

These are the files I have: .dir { color: white; font-family: "Lucida Console", Monaco, monospace; font-size: 16px; } .cmdline { font-family: "Lucida Console", Monaco, monospace; background-color: black; border: 1px solid black; color: whi ...

How can you use mouseover events to display a popover and manipulate the div id?

In my scenario, I have multiple div elements and I want to display separate popover for each div. Initially, the popover is not shown on the first mouseover event but works perfectly on subsequent attempts. Below is the code snippet: $(document).read ...

"Utilizing jQuery and AJAX to manage identical-named option boxes with

I am encountering an issue with multiple select boxes that share the same name. Currently, when I choose a value from one select box, it submits that selection and updates the database. However, when I select an item from another select box, it still submi ...

Issue with Bootstrap Carousel function in desktop browsers but functioning correctly on mobile devices

I'm experiencing issues with my bootstrap carousel on mobile browsers, but not on web browsers, despite trying various fixes and clearing my browser cache. Specifically, there is no sliding effect when clicking on the indicator, and everything else ap ...

How can I change an array to a string in JavaScript/jQuery and add a specific

Currently, I am tasked with the challenge of converting an array into objects. Furthermore, I also need to add something before each object is displayed. var arrayList = ["image1.jpg","image2.jpg","image3.jpg"]; The desired outcome should look like this ...

Having trouble displaying a popup dialog box in ASP.NET using JavaScript

I am trying to implement a popup dialog box in ASP.NET using JavaScript, but it's not working as expected! Below is the code I am using: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal< ...

Calculate the result by multiplying each row value with the value provided as input

Check out this HTML code snippet <form><input type="number"></form> <table class="my-table"> <thead> <tr> <td>Header 1</td> <td>Header 2</td> </tr> </thead> &l ...

Shipment calculation involves the consideration of factors such as the quantity,

Hello, my name is Mirella and I am from Italy. Please bear with me as I communicate through Google Translate. I am facing some issues with shipping costs while using Simplecart. My customers have varying shipping costs based on the items they purchase. T ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

Using EMCC and WASM on the web, what is the best way to utilize a C function?

I am currently working on a basic website that showcases the outcome of a function call from a javascript file that interacts with a WASM file. Here are the files I have set up: Makefile FILES = add.c OUTPUT = MyWasmLib CC = emcc EMCC_VERSION := $(shell c ...

The Javascript code for sleep execution is operational, yet it appears to be not inducing any noticeable delays

This Angular app contains code that runs inside a webworker written in Typescript. As someone new to working with webworkers, I have encountered an issue where both the sleep function and the loop seem to be executing within the same thread. The main goal ...

The ExpressJS Req.method TypeError occurs when attempting to read the 'method' property of an undefined object

My node express server is throwing an error: Error in index.js. const bodyParser = require('body-parser'), express = require('express'), path = require('path'); const config = require('./config'); con ...

Meteor: dynamic approach to assigning array values in Spacebars

It's hard to put this into words... I have a collection with an array, and as I iterate through it, I've been setting colors.[0].imageLink without changing the [0]. Now, I want this to be dynamic based on the value of a function (in this case, th ...

Print out the error message: "ERROR [ExceptionsHandler] Unable to access the property 'log' as it is undefined."

Just starting out with Nestjs and JavaScript but ran into an error when trying to print a text line using console.log() const my_text ="123" console.log(my_text) https://i.sstatic.net/xPnzX.png ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

Having trouble accessing the menu in the dropdown div when clicking back?

I am working on creating a menu that drops down from the top of the page using JQuery. I have everything set up with the code below: <div id="menu"> <div id="menucontentwrapper"> <div id="menucontent"></div> </di ...