当我运行此功能时,在Ionic4应用程序(带有Angular 7和Typescript 3)中:
public addDeviceMarkers(devicePositions: Array<any>): void {
devicePositions.map(function(device) {
const position = {lat: device.latitude, lng: device.longitude};
const marker = new google.maps.Marker({
position: position,
title: device.deviceId
});
marker.setMap(this.map);
});
}
我遇到此错误:
core.js:15724 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined
at google-map.component.ts:214
我已经解决了问题,以这种方式修改了功能:
public addDeviceMarkers(devicePositions: Array<any>): void {
const mapObject = this.map;
devicePositions.map(function(device) {
const position = {lat: device.latitude, lng: device.longitude};
const marker = new google.maps.Marker({
position: position,
title: device.deviceId
});
marker.setMap(mapObject);
});
}
我必须定义const mapObject = this.map;
。
问题是,为什么进入映射循环this
是未定义的?
答案 0 :(得分:0)
您无需声明即可实现
const mapObject = this.map;
public addDeviceMarkers(devicePositions: Array<any>): void {
var selfRef = this;
devicePositions.map(function(device) {
const position = {lat: device.latitude, lng: device.longitude};
const marker = new google.maps.Marker({
position: position,
title: device.deviceId
});
marker.setMap(selfRef.map);
});
}