IONIC 2 - 无法检索 ionViewDidLoad() 中的数组



我想从restApi检索地点坐标并在地图上显示它们。 我收到错误:无法读取未定义的属性"长度">

请帮助我! 我希望您告诉我如何获取数据以添加多个标记。

这是我的代码部分

import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { RestProvider } from '../../providers/rest/rest';
declare var google;
@Component({
selector: 'page-localisation',
templateUrl: 'localisation.html',
})
export class LocalisationPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
places: Array<any>;
errorMessage : string;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation, public rest: RestProvider) {
}
ionViewDidLoad(){
this.loadMap();
this.getPlaces();
this.addPlacesToMap()
console.log("Length : " + this.places.length) ; //Error Cannot read property 'length' of undefined
}
getPlaces() {
this.rest.getPlaces().subscribe(
places => this.places = places,
error => this.errorMessage = <any>error
);
}
loadMap(){
let latLng = new google.maps.LatLng(-4.066548, 5.356315);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
addPlacesToMap(){
//...
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
});
content: content
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}

ionViewDidLoad 在 "this.rest.getPlaces().subscribe" 完成之前启动...所以你的变量"位置"是空的

将获取地点更改为承诺

async getPlaces() {
places = await this.rest.getPlaces() ;
return places
}

然后在ionViewDidLoad中

ionViewDidLoad(){
var that = this ;
this.loadMap();
this.getPlaces().then((places)=>{
that.places = places;
console.log("Length : " + that.places.length) ; 
});
this.addPlacesToMap()
}

相关内容

  • 没有找到相关文章

最新更新