javascript - Angular TypeScript JavaScript 词典范围在第三方 API 事件处理程序的嵌套函数中丢失

标签 javascript angular typescript scope nested-function

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

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

最佳答案

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

关于javascript - Angular TypeScript JavaScript 词典范围在第三方 API 事件处理程序的嵌套函数中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669884/

相关文章:

javascript - html页面自动提交 - javascript填充隐藏字段

angular - ngrx - createSelector 与 Observable.combineLatest

javascript - 与 RxJS 流冲突的条件语句

css - ionic 3 响应弹出窗口大小

javascript - Ava 单元测试因 TypeScript 失败 ("SyntaxError: Unexpected identifier")

javascript - 谷歌地图 api 方向服务在显示多个标记 javascript 之间的路线时提供 OVER_QUERY_LIMIT

javascript - 将 React 升级到 0.13.2 会导致 : "Uncaught TypeError: Cannot read property ' _currentElement' of null"

javascript - Ember.js CLI 构建西兰花漏斗不工作

node.js - ng2-test-seed 无法统计 - 没有这样的文件或目录

node.js - 在服务器上通过 Http 请求的 URL 必须是绝对的