angular - 无法在 OpenLayers 函数中调用打字稿函数
问题描述
我在 Angular 中使用 OpenLayers 和 TypeScript 时遇到问题。我的 ol 地图有一个事件监听器
this.map.on('click', function (e) {
let x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
this.addMarker(x[0], x[1]);
});
x[0] 和 x[1] 是我的纬度和经度值。如果我调用函数 addMarker 我会在点击地图时收到错误消息:
ERROR TypeError: this.addMarker is not a function
at Map.<anonymous> (map.component.ts:90)
at Map.push.../node_modules/ol/events/Target.js.Target.dispatchEvent (Target.js:113)
at Map.push.../node_modules/ol/PluggableMap.js.PluggableMap.handleMapBrowserEvent (PluggableMap.js:871)
at MapBrowserEventHandler.push.../node_modules/ol/events/Target.js.Target.dispatchEvent (Target.js:113)
at MapBrowserEventHandler.push.../node_modules/ol/MapBrowserEventHandler.js.MapBrowserEventHandler.emulateClick_ (MapBrowserEventHandler.js:97)
at MapBrowserEventHandler.push.../node_modules/ol/MapBrowserEventHandler.js.MapBrowserEventHandler.handlePointerUp_ (MapBrowserEventHandler.js:148)
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
这是我的 addMarker 方法:
addMarker(lon, lat) {
let marker = new Feature({
geometry: new Point(transform([lon + 0.01, lat], 'EPSG:4326', 'EPSG:3857'))
});
this.source.addFeature(marker);
}
我不知道如何解决此问题或是否有解决方法。
我希望你能在这里帮助我。
解决方案
这里的问题是您使用的语法。在this.map
. 你可以做两件事。
- 使用箭头功能(推荐)。
this.map.on('click', (e) => {
const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
this.addMarker(x[0], x[1]);
});
- 存储
this
在变量中,然后使用该变量。
const _that = this;
this.map.on('click', function(e) {
const x = transform(e.coordinate, 'EPSG:3857', 'EPSG:4326')
_that.addMarker(x[0], x[1]);
});
原因是,范围this
。当你创建这样的function(){}
函数时,指的是这个函数,但是当你使用arrow
函数时,this
将引用class
.
推荐阅读
- html - 是否可以在一个 HTML 页面中添加几个 bgcolor,而不是背景颜色
- html - 如何以角度消失装载机
- c++ - 动态链接 - Linux Vs。视窗
- javascript - MODAL:在 Modal 中显示和隐藏 div
- c# - 在 .Net Core Web Api 中读取 LocalStorage 值
- jquery - jquery中的窗口onload事件没有触发
- react-native - React Native:将本地 PDF 文件保存到用户设备
- javascript - 如何在 jquery 中的 beforeSend() 上延迟加载程序
- c# - 序列在 asp core 和 sql server 2016 中不包含任何元素
- iteration - Gekko 处理代数/隐式循环