Openalyers4 Angular5 无法将信息添加到变量
Openalyers4 Angular5 can`t add info to variable
我有一个奇怪的错误。当我将 layerinformation 放入局部变量时它起作用但是当我尝试将它放入我想在整个组件中使用的变量时它给出了这个错误:
ERROR TypeError: Cannot read property 'setLayer' of undefined
这是我的代码:
this.map.getLayers().forEach(function(layer, i) {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
}
});
上面的代码工作正常,但是当我将 var layerinfo 更改为 this.setLayer 时,我得到了 TypeError 有人能解释一下为什么吗?
谢谢!
只需使用箭头函数
this.map.getLayers().forEach((layer, i) => {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
}
});
您需要使用箭头函数。如果您使用这样的函数,那么您的 this 范围仅限于您的函数。
传统函数
public myTest:string = "mytest";
(....)
this.map.getLayers().forEach(function(layer, i) {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
console.log(this.myTest);
}
});
所以在这个例子中,this 是未定义的,因为我们可以访问你组件的 this(仅限函数范围!)
箭头函数
public myTest:string = "mytest";
(....)
this.map.getLayers().forEach((layer, i) => {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
console.log(this.myTest);
}
});
在第二个示例中,您可以显示 this.myTest (mytest) 的结果。因为你的这个组件在箭头函数中可用。
你的情况
所以在你的情况下:
public setLayer(){
(...)
}
this.map.getLayers().forEach((layer, i) => {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
this.setLayer();
}
});
If you want more informations about that
我有一个奇怪的错误。当我将 layerinformation 放入局部变量时它起作用但是当我尝试将它放入我想在整个组件中使用的变量时它给出了这个错误:
ERROR TypeError: Cannot read property 'setLayer' of undefined
这是我的代码:
this.map.getLayers().forEach(function(layer, i) {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
}
});
上面的代码工作正常,但是当我将 var layerinfo 更改为 this.setLayer 时,我得到了 TypeError 有人能解释一下为什么吗?
谢谢!
只需使用箭头函数
this.map.getLayers().forEach((layer, i) => {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
}
});
您需要使用箭头函数。如果您使用这样的函数,那么您的 this 范围仅限于您的函数。
传统函数
public myTest:string = "mytest";
(....)
this.map.getLayers().forEach(function(layer, i) {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
console.log(this.myTest);
}
});
所以在这个例子中,this 是未定义的,因为我们可以访问你组件的 this(仅限函数范围!)
箭头函数
public myTest:string = "mytest";
(....)
this.map.getLayers().forEach((layer, i) => {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
console.log(this.myTest);
}
});
在第二个示例中,您可以显示 this.myTest (mytest) 的结果。因为你的这个组件在箭头函数中可用。
你的情况
所以在你的情况下:
public setLayer(){
(...)
}
this.map.getLayers().forEach((layer, i) => {
if (layer instanceof Group) {
var layerinfo = layer.getLayers();
this.setLayer();
}
});
If you want more informations about that