The Angular TypeScript lexicon scope becomes obscured when nested within a third-party API event handler function

I'm having trouble managing scope context in an Angular component while working with a third-party API (ESRI ArcGIS JavaScript API 4.7). I am specifically struggling when trying to handle an event from the ArcGIS API using their event handler callback. If you click on the map, you'll encounter the error. I believe there should be a way to resolve this issue by handling context properly, but so far, my attempts have been unsuccessful. Closures are not my forte. Any assistance would be greatly appreciated.

Visit this link for more details

 ngOnInit() {
    this.arcgisService.loaded$.subscribe(loaded => {
      console.log("map loaded subscription");
      if(loaded) {
        this.arcgisService.constructMap({basemap: this.basemap, elevation: true}).then(map => {
          this.arcgisService.constructMapView(
            { 
            map: map,
            container: this.id,
            center: [-117.18, 34.06],
            zoom: 15
            }
            ).then(mapView => {
              console.log("constructMap.then");
              console.log(this); 
              this.mapView = mapView;
              mapView.on("click", function(event) {
                 //this.test = event.x
                 this.onMapClick(event.x)
                  console.log("click event: ", event.x);
                });
              })
        })//end construct map
      }
    })
  }

onMapClick(x){
  console.log(x)
}

Answer №1

Every new function that is created by a function statement defines its own 'this' value based on how the function was called. Therefore, using an arrow function will reference the current object.

Give this a try

ngOnInit() {
    this.arcgisService.loaded$.subscribe(loaded => {
      console.log("Subscribed to map loaded event");
      if(loaded) {
        this.arcgisService.constructMap({basemap: this.basemap, elevation: true}).then(map => {
          this.arcgisService.constructMapView(
            { 
            map: map, 
            container: this.id,
            center: [-117.18, 34.06],
            zoom: 15
            }
            ).then(mapView => {
              console.log("Handling constructMap.then");
              console.log(this); 
              this.mapView = mapView;
              //Use arrow function here to refer to the current object
              mapView.on("click", (event) => {
                 //this.test = event.x
                 this.onMapClick(event.x)
                  console.log("Received click event: ", event.x);
                });
              })
        })//end construct map
      }
    })
  }

Check out the Forked Example

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

Maintain the default type for the generic type parameter

I am attempting to work around a few optional generic type parameters and keep them as defaults that have already been set. Here is a sample code snippet: interface Foo<T, T1 = string, T2 = boolean> { ID: T Name: T1 IsActive: T2 } There ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

Is it possible to connect a JavaScript file to an HTML document within a React application?

I have been developing a React website with the following file structure: public: index.html second.html src: index.js second.js table.js forms.js The main page (index.js) contains both a form and a table. One of the columns in the table has a link t ...

What is the best way to create a more compact Select component in React?

Working on React's Select component has been quite the challenge for me. I'm in the process of creating a simple dropdown button, also known as a ComboBox, similar to what can be seen on GitHub Insights: https://i.stack.imgur.com/J9Bcd.png Belo ...

Guide to delivering a PDF document from a controller

In my pursuit to send a PDF file from a Controller Endpoint using NestJs, I encountered an interesting issue. Without setting the Content-type header, the data returned by getDocumentFile function is successfully delivered to the user. However, when I do ...

TypeScript interfaces do not strictly enforce properties when an object is assigned

Can someone help me understand TypeScript's rules for interfaces better? I am confused about why the following block of code throws an error due to the id property missing from the interface: interface Person { name: string; } let person: Person = ...

The images on the right are transitioning between slides, but the ones on the left seem to be frozen on the

https://i.sstatic.net/qKwbP.jpgI am experiencing an issue with my two changing image galleries placed side by side. The right image gallery is functioning properly and switching slides, but the left one seems to be stuck on the first slide. I sourced the c ...

php$insert new field into mysql table using form insertcell

How do I insert a column in MySQL? I am struggling with the insertCell form. I have tried but I can't seem to add a MySQL column using my JavaScript code with PHP. I am familiar with Php PDO, but this seems difficult to me. Can someone guide me on ho ...

What is preventing React CLI from installing the template as TypeScript?

When I run npm init react-app new-app --template typescript, it only generates a Javascript template project instead of a Typescript one. How can I create a Typescript project using the CLI? Current Node JS version: 15.9.0 NPM version: 7.0.15 ...

Retrieve text from a dropdown menu while excluding any numerical values with the help of jQuery

I am currently implementing a Bootstrap dropdown menu along with jQuery to update the default <span class="selected">All</span> with the text of the selected item by the user. However, my objective is to display only the text of the selected it ...

ReactJS implementation for selecting names from a dropdown menu

Hello, I am new to using React. I have a dropdown form with a search engine in it that is working perfectly as I need. The only issue is that when I type, for example, AR in the Symbol field, it shows me ARDRBTC as expected, but I am unable to click on it ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

What is the simplest method to create a scroller for engaging narratives?

I am in the process of creating a static but responsive storytelling website using HTML. My objective is to create an effect similar to this: https://i.stack.imgur.com/zIEpU.gif The idea is to have text on the left and a *.jpg image fixed on the right. As ...

Error: Unable to use 'ngForFrom' as it is not a recognized native property for binding

I have looked for solutions here and here. I am currently using angular 2 version 2.0.0-beta.7, but encountering the following error: EXCEPTION: Template parse errors: Can't bind to 'ngForFrom' since it isn't a known native property (" ...

What is the best method for retrieving objects from a Meteor collection?

I'm a beginner with Meteor and I'm currently working on the introductory tutorial. However, I'm facing difficulties in retrieving data from a collection. Below is my JavaScript code: import angular from 'angular'; import angularM ...

Troubleshooting issue in Typescript with useFieldArray relating to property name

I am encountering an issue with useFieldArray in TypeScript. The problem arises when trying to specify the controller's name as: name={test.${index}.firstname} The error message reads: controller.d.ts(18, 5): The expected type comes from property &ap ...

Error encountered: Unexpected character 'C' found at the beginning of the JSON data

Hey there, I'm new to all of this so just trying to figure it out! :) I stumbled upon a GitHub project that I really want to work on and understand in order to create my own solution. The project can be found at the following link: https://github.com ...

How do I make the message "document.getElementById(...) is null" become true?

When running my code, only two of the document.getElementById calls (ctx1 and ctx2) successfully get values while the others (such as ctx3) do not. How can I ensure that all elements retrieve their values without receiving an error message? Below is a snip ...

Warning in React js: [eslint] srcApp.js Line 2:8 - The variable 'person' is declared but not utilized

[![I need assistance with this problem. Whenever I try to resolve it, I consistently encounter the same error on Line 2:8: 'person' is defined but never used - no-unused-vars.][1]][1] ...

Fetching information from server proves to be sluggish within AngularJS application

In the process of developing a web application, I am faced with the task of sending numerous $http requests to the server. My front-end is built using AngularJS while the back-end utilizes ExpressJS. The $http requests are currently being made as shown in ...