单击地图上的 angular2 openlayers 显示详细信息

angular2 openlayers on click map show details

在angular2组件中,在ngOnInit中,我想获取openlayers map click上的元素id。这是我的代码:

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

但是当我点击地图时出现错误,提示我无法调用未定义的函数 'getFeatureDetail',我也尝试将 id 保存在全局变量上,但它并没有解决我的问题。

尝试使用箭头功能 (=>) 而不是输入功能。它在词汇上捕捉到了 this 的意思。

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

问题是,您正在将 this 的值丢失到您的回调范围中,因为它引用另一个没有 myService 实例的对象。

如果您将对建议对象的引用保存到另一个变量(_thisselfme 等),它可以稍后使用该变量。

关注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)
              .suscribe(data => this.myArray = data)
        })
    });

@Fatal 的回答有效,因为 Lambda(粗箭头)函数的作用完全相同(如果它被编译成 ES5),是的,这是这种情况下最舒适的方法。

但了解幕后发生的事情在某些情况下至关重要。

请同时阅读这篇文章(阅读 2 分钟)article