【问题标题】:angular2 openlayers on click map show details点击地图上的 angular2 openlayers 显示详细信息
【发布时间】:2016-11-22 22:39:43
【问题描述】:

在 angular2 组件中,在 ngOnInit 中,我想在 openlayers 地图单击时获取元素 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 保存在全局变量中,但它不能解决我的问题。

【问题讨论】:

    标签: javascript angular typescript onclick openlayers-3


    【解决方案1】:

    尝试使用箭头函数 (=>) 而不是键入函数。它在词汇上捕捉到了 this 的含义。

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

    【讨论】:

    • 我认为您必须扩展您的答案并解释您的解决方案为什么有效以及有什么区别。
    【解决方案2】:

    问题是,您正在将 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

    【讨论】:

      猜你喜欢
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2012-12-20
      相关资源
      最近更新 更多