0

我正在尝试处理来自第三方 API(ESRI ArcGIS JavaScript API 4.7)的事件。当我尝试使用其事件处理程序回调处理来自 ArcGIS API 的事件时,我正在努力控制加载 API 的 Angular 组件中的范围上下文。单击地图以引发错误。我觉得必须有一种方法可以通过控制上下文来完成这项工作,但我无法让它发挥作用。闭包不是我的强项。任何帮助都会很棒。

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)
}
4

1 回答 1

1

每个由 function 语句创建的新函数,都会根据函数的调用方式定义自己的 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
      }
    })
  }

分叉示例

于 2020-01-09T18:17:14.493 回答