Angular 中的开放层

Openlayers in Angular

我在 OpenLayers 地图上有点击功能

testvar: string
map = new Map()


ngOnInit(): void {

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

}

但是this在点击功能范围内不可用

任何想法如何做到这一点/

这是因为您使用 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/