【问题标题】:Angular 2 + Openlayers 3, Loses the component reference when I add the function to an interactionAngular 2 + Openlayers 3,当我将函数添加到交互时丢失组件引用
【发布时间】:2016-12-08 19:38:47
【问题描述】:

当我使用其属性中定义的方法创建新交互时,我需要保留我的组件引用。举个例子:

在 DrawComponent.ts 中:

@Input() map:any;
layer:any;

// Filters functions
layerFilter(itemLayer:any) {
    console.log(this) 
    return (itemLayer === this.layer);
};

// Init select interaction
select = new ol.interaction.Select({
    layers: this.layerFilter
});

// Add select interaction to the map
this.map.addInteraction(this.select);

layerFilter 内的控制台日志返回 NULL,因为我丢失了组件引用。

你有解决办法或解释吗?

【问题讨论】:

    标签: angular typescript openlayers-3


    【解决方案1】:

    也许您可以使用箭头函数来避免更改“this”上下文。

    @Input() map:any;
    layer:any;
    
    // Filters functions
    layerFilter = (itemLayer:any) => {
        console.log(this) 
        return (itemLayer === this.layer);
    };
    
    // Init select interaction
    select = new ol.interaction.Select({
        layers: this.layerFilter
    });
    
    // Add select interaction to the map
    this.map.addInteraction(this.select);
    

    【讨论】:

      【解决方案2】:

      对于那些会遇到同样问题的人,我找到了一个解决方案,但我不知道这是否是一个好习惯。

      我使用函数 .bind() 将组件的上下文绑定到我的方法

      // Init select interaction
      select = new ol.interaction.Select({
           layers: this.layerFilter.bind(this);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多