0

I'm trying to handle an event from a third party API (ESRI ArcGIS JavaScript API 4.7). I'm struggling with controlling scope context in an Angular component that loads the API when I try to handle and event from the ArcGIS API using their event handler callback. Click on the map to elicit the error. I feel like there must be a way to make this work with by controlling the context, but I haven’t been able to make it work. Closures aren’t my strong suit. Any help would be great.

https://stackblitz.com/edit/angular6-arcgis-api-5yfayy?file=src%2Fapp%2Fcomponents%2Fmap.component.ts

 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)
}
AliWieckowicz
  • 549
  • 1
  • 4
  • 17

1 Answers1

1

Every new function created by function statement, defined its own this value based on how the function was called. so using arrow function will refer to current object

Try this

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;
              //Use arrow function here to refer current object
              mapView.on("click", (event) => {
                 //this.test = event.x
                 this.onMapClick(event.x)
                  console.log("click event: ", event.x);
                });
              })
        })//end construct map
      }
    })
  }

Forked Example

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60