Ionic v4-为什么我的get函数返回未定义?

时间:2019-05-21 03:16:25

标签: angular typescript ionic-framework

我试图获取位置,所以一开始我尝试保存纬度和经度,但是声明的变量从不返回任何内容。

这是我的代码:

public device_location: any = {};

constructor(private geolocation: Geolocation) {
this.setGeolocation();
this.getGeolocation();
}

setGeolocation(){
   this.geolocation.getCurrentPosition().then((resp) => {
       // resp.coords.latitude
       this.device_location.latitude = resp.coords.latitude;
       this.device_location.longitude = resp.coords.longitude;
       console.log( this.device_location.longitude);
       }).catch((error) => {
   console.log('Error getting location', error);
 });

 let watch = this.geolocation.watchPosition();
 watch.subscribe((data) => {
// data can be a set of coordinates, or an error (if an error occurred).
// data.coords.latitude
// data.coords.longitude
 });
}

getGeolocation(){
    console.log( JSON.stringify(this.device_location) );
    return this.device_location;
}

这是输出:

  

123.45600   {}

1 个答案:

答案 0 :(得分:0)

从构造函数中删除它:

this.getGeolocation();

,然后在此方法中这样调用它:

setGeolocation(){
this.geolocation.getCurrentPosition().then((resp) => {
   // resp.coords.latitude
   this.device_location.latitude = resp.coords.latitude;
   this.device_location.longitude = resp.coords.longitude;

   this.getGeolocation();



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