我在onInit方法中有以下监听器:
google.maps.event.addListener(this.map, 'click', function(event) {
console.log(event.latLng);
var lt = event.latLng.lat;
var ln = event.latLng.lng;
console.log(lt());
console.log(ln());
this.onStoreMarker(lt(),ln());
});
外面我有一个方法,当事件被触发时被调用,Angular2编译得很好但是当我尝试通过点击运行应用程序时激活事件我得到一个错误说
未捕获的TypeError:this.onStoreMarker不是函数
onStoreMarker(lt: number,ln: number) {
var newStore = prompt("Please enter your store name", "Store Name");
var location = {lat: lt, lng: ln};
var marker = new google.maps.Marker({
position: location,
map: this.map,
title: newStore,
});
}
答案 0 :(得分:4)
更改
google.maps.event.addListener(this.map, 'click', function(event) {
与
google.maps.event.addListener(this.map, 'click', (event)=> {
您的this
未提及您的组件。
或者,旧的js方式:
var self = this; // store this in a variable to use it later
google.maps.event.addListener(this.map, 'click', function(event) {
console.log(event.latLng);
var lt = event.latLng.lat;
var ln = event.latLng.lng;
console.log(lt());
console.log(ln());
self.onStoreMarker(lt(),ln()); // <-- use it later
});
我建议您阅读本文以获得更深入的答案:How to access the correct `this` inside a callback?