[英]How to call a typescript function inside callback of a JavaScript
我正在Angular 5前端框架中使用javascript Google Maps组件
export class MapComponent implements OnInit {
ngOnInit() {
this.initializeGMap()
}
initializeGMap() {
var myLatlng = new google.maps.LatLng(12,77);
var mapOptions = {
zoom: DEFAULT_MAP_ZOOM,
center: myLatlng,
scrollwheel: true,
styles: MAP_STYLE
};
this.map = new google.maps.Map(document.getElementById("map"), mapOptions);
this.initOnMapClickListener();
}
initOnMapClickListener() {
google.maps.event.addListener(this.map, 'click', function(event) {
var selectedLocation = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
this.addMarker(selectedLocation)
});
}
addMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: this.map,
icon: './assets/map_marker.png'
});
}
}
上面是我的打字稿文件,它具有三个功能
未捕获的TypeError:无法读取null的属性'addMarker'
这是运行Angular应用程序时出现的控制台错误
请帮助了解如何在Javascript回调中调用Typescript函数
尝试使用箭头函数调用函数=>
像这样结合的laxical范围this
-
initOnMapClickListener() {
google.maps.event.addListener(this.map, 'click', (event) => {
var selectedLocation = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
this.addMarker(selectedLocation)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.