Show details on map click with Angular's OpenLayers integration

When working with an Angular2 component, I am trying to retrieve the element id on a click event on an OpenLayers map within the ngOnInit function. Below is the code I am using:

map.on("click", (e) => {
    map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
        let id: number = feature.getId();
        this.myService.getFeatureDetail(id)
          .suscribe(data => this.myArray = data)
    })
});

Unfortunately, I am encountering an error when clicking on the map that states I cannot call the function 'getFeatureDetail' of undefined. I have also attempted to save the id in a global variable, but this does not resolve the issue.

Answer №1

Consider utilizing arrow functions (=>) instead of typing out the function keyword. Arrow functions effectively capture the meaning of the 'this' keyword.

 map.on("click", (e) => {
     map.forEachFeatureAtPixel(e.pixel, (feature, layer) => {
         // Your code here
     }) 
 });

Answer №2

The issue lies in the fact that the value of this is being lost in your callback scope, as it is referencing a different object that does not contain an instance of myService.

If you save a reference to your advice object in another variable (_this, self, me, etc.), you can use that variable later on.

For more information, refer to this link.

map.on("click", (e) => {
        var _this = this;
        map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
            let id: number = feature.getId();
            _this.myService.getFeatureDetail(id)
              .subscribe(data => this.myArray = data)
        })
    });

@Fatal's answer works because the Lambda (Fat arrow) function does the same thing (when compiled into ES5), and yes, it is the most convenient approach for this scenario.

However, understanding what is happening behind the scenes is essential in certain situations.

Take a moment to read this quick (2 min read) article as well.

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

Angular 2 is not compatible with custom reuse strategy when implementing lazy loading for modules

I attempted to implement a custom route reuse strategy in my angular2 project, but I encountered issues with lazy loading of modules. Does anyone have insight on this matter? My project is using angular 2.6.4. Here is the code for the custom route-reuse-s ...

Animation using jQuery is functional on most browsers, however, it seems to

After creating an animation to simulate an opening door using jQuery, I discovered that it works perfectly on Firefox 24, Chrome 28, and IE 8. However, Safari presents a problem - the door opens but then the "closed" door reappears at the end of the animat ...

Angular Material Clock Picker for 24-Hour Time Selection

Struggling to find a time picker component that supports the 24-hour format for my Angular 14 and Material UI application. Can anyone help? ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

EJS failing to render HTML within script tags

Here is some code that I'm working with: <% // accessing content from a cdn api cloudinary.api.resources( { type: 'upload', prefix: '' }, (error, result) => { const assets = result.r ...

Guide to transferring text to clipboard using PHP and JS

Forgive me if this sounds a bit silly. I've been trying to figure this out for a while now, and it seems like the only solution I found involves clicking some sort of button. I have a form that generates license keys, and after generating one, I wan ...

Updating all images in a JQuery thumbnail gallery

I've been experimenting with jQuery and fancy box to create a special effect on my website. I wanted to display a large image with thumbnails below it, where clicking on a thumbnail would update the main image (similar to the RACE Twelve image example ...

Refresh Next.js on Navigation

Is there a way to trigger a reload when clicking on a Link component from next/link? I attempted to create my own function within the child div of the link that would reload upon click. However, it seems to reload before the route changes and is not succ ...

Utilizing one-way data binding with Angular 2 in HTML is similar to the approach used in Angular 1, employing the

Is there a method in Angular 2 to achieve one-way data binding similar to what we did in Angular 1? <!DOCTYPE html> <html lang="en-US"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> &l ...

Importing an array of Vue components to be exported and utilized in the app.js file

I'm currently working on a Laravel 8 project with vue.js v2.6 and I want to clean up my app.js file by moving all of my Vue.component() declarations to a separate file. To achieve this, I created js/vueComponents.js where I placed all the vue componen ...

Tips for eliminating nested switchMaps with early returns

In my project, I have implemented 3 different endpoints that return upcoming, current, and past events. The requirement is to display only the event that is the farthest in the future without making unnecessary calls to all endpoints at once. To achieve th ...

What could be causing the fourth tab to not show any data while the first three tabs are functioning as expected?

I've encountered an issue with my HTML tabs. While I can easily switch between the first three tabs and view their content, tab 4 doesn't seem to display its associated data. It's puzzling why tab 4 is not working when the others are functio ...

Unable to simulate a service and retrieve information in an angular unit test - showing as undefined

In my current project, I have a component that I am trying to write unit tests for. However, when I run the test, I noticed that the value of console.log('**fav**' + favorite[`isFavorite`]); shows up as undefined. This indicates that the data I ...

Exploring ways to store session data in Next.js 13 with Supabase for seamless persistence

Encountering an issue with next-auth. Upon logging in, the result shows ({error: 'SessionRequired', status: 200, ok: true, url: null}), despite having an active session. The console also displays this error message, which I believe may be related ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...

Unveiling the significance behind the utilization of the.reduce() function in conjunction with Object.assign()

After consulting the method/object definitions on MDN, I am attempting to create a simplified step-by-step explanation of how the script below (referenced from a previous post) is functioning. This will not only aid in my understanding but also help me ada ...

Run the Ionic function only when the app is launched for the first time

I'm facing an issue with a function in Ionic storage that sets an array to default values. I only want this function to run the first time the app is launched on a user's phone, but currently it runs every time the app is opened because it's ...

Sending form data to the server using JavaScript: A step-by-step guide

Currently, I am dealing with the configuration of two servers. One server is running on React at address http://localhost:3000/contact, while the other is powered by Express at address http://localhost:5000/. My goal is to transmit form data as an object v ...

Is it possible to utilize a service that is already being used by the imported component?

Recently, I began working with Angular2 and have been quite impressed with it. However, today I encountered a challenge: I have a reusable alert component that utilizes its own service containing business logic. My question is, can I utilize the same serv ...