Angular 2 + Openlayers 3,当我将函数添加到交互时丢失组件引用

Angular 2 + Openlayers 3, Loses the component reference when I add the function to an interaction

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

在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 中的控制台日志 return NULL 因为我丢失了我的组件引用。

你有解决办法或解释吗?

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

我使用函数 .bind()

将我的组件的上下文绑定到我的方法
// Init select interaction
select = new ol.interaction.Select({
     layers: this.layerFilter.bind(this);
});

也许您可以使用箭头函数来避免 "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);