Ionic服务显示此错误Ionic2

时间:2017-04-01 06:21:18

标签: angular typescript ionic-framework ionic2

在这个打字稿代码中我定义public currentLocation : {lat: number, lng: number};,我在currentLocation中的this.geolocation方法中得到console.log(this.currentLocation)的值。但是在console.log(this.currentLocation)的这个街区之外,我得到了定义。我怎样才能在全局变量中获得价值?

export class DetailsPage {

  typeDetails: {};

  public currentLocation : {lat: number, lng: number};

   posOptions = {
  enableHighAccuracy: true,
  timeout: 20000,
  maximumAge: 0
};



  constructor(public navCtrl: NavController,
          public navParams: NavParams,
          private typeApi : TypeApi,
          public geolocation : Geolocation) {}


  ionViewDidLoad() {
  let baseUrl  ='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2150756,72.8880545&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg';
    this.geolocation.getCurrentPosition().then((resp) => {

      this.currentLocation ={
          lat :resp.coords.latitude,
          lng :resp.coords.longitude

      };

 console.log(this.currentLocation);


    }).catch((error) => {
      console.log('Error getting location', error);
    });


  console.log(this.currentLocation);



console.log('ionViewDidLoad DetailsPage');

     //this.typeDetails = this.typeApi.getTypeDetails();
     //console.log(this.typeDetails);

    this.typeApi.getTypeDetails().then(data => {
    this.typeDetails = data;
    console.log(this.typeDetails);
  });
  }


}

1 个答案:

答案 0 :(得分:1)

因此promise您需要在console.log(this.currentLocation);方法中使用resolve,如下所示。由于async性质,您无法将其记录在promise之外{1}}。B'您不知道它会在哪个时刻拥有价值。

this.geolocation.getCurrentPosition().then((resp) => {

      this.currentLocation ={
          lat :resp.coords.latitude,
          lng :resp.coords.longitude

      };

    console.log(this.currentLocation);//here you have to use log method

    }).catch((error) => {
      console.log('Error getting location', error);
    });