我想添加一个对象数组,但它不起作用:Can not set property '0' of undefined
我尝试输入this.positions [0] = PositionMap对象
我减少了代码的大小以提高可读性,但其余的工作
这是我的代码:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Geolocation } from 'ionic-native';
declare var google;
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
positions: PositionMap[] = [];
@ViewChild('map') mapElement: ElementRef;
constructor(public navCtrl: NavController) {
this.positions = [];
}
ionViewDidLoad(){
this.loadMap();
this.autocomplete();
}
autocomplete() {
autocompleteDepart.addListener('place_changed', function() {
var place = autocompleteDepart.getPlace();
let tmpPosition = new PositionMap(place.geometry.location.lat(), place.geometry.location.lng());
this.positions[0] = (tmpPosition);
return;
});
}
}
export class PositionMap {
latitude: number;
longitude: number;
constructor(_latitude: number, _longitude: number) {
this.latitude = _latitude;
this.longitude = _longitude;
}
}
我的表在类和构造函数中声明得很好,但在函数中却不知道。
答案 0 :(得分:2)
您正在使用回调函数中的this
。必须首先将此回调函数绑定到this
。最简单的方法是使用箭头功能:
autocompleteDepart.addListener('place_changed', () => {
...
});