Openlayers in Angular



我有一个点击功能的OpenLayers地图

testvar: string
map = new Map()

ngOnInit(): void {
this.map.on('click', function(event) {
console.log(this.testvar)
})
}

this在click功能范围内不可用。

你知道怎么做吗/

这是因为您使用function关键字声明函数。如果您将函数声明为箭头函数,它将工作:

this.map.on('click', event => {
console.log(this.testvar)
})

查看这篇文章,了解更多关于箭头函数与函数的详细信息:https://www.freecodecamp.org/news/when-and-why-you-should-use-es6-arrow-functions-and-when-you-shouldnt-3d851d7f0b26/

或者这个:https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/

最新更新