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

时间:2018-02-08 18:00:10

标签: ionic-framework ionic2

我想从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);
    });
  }

}

1 个答案:

答案 0 :(得分:0)

ionViewDidLoad在&#34; this.rest.getPlaces()。subscribe&#34;之前启动。已完成...所以你的变量&#34;地点&#34;是NULL

将getPlaces更改为Promise

 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()

  }