1

我非常喜欢Nativescript(带有anngular2/typescript)。我的用例是使用nativescript地理定位插件跟踪用户的位置,并保存结果(如经度和纬度)以备后用。下面是我的示例代码:如何在本地变量中保存地理位置详细信息以便稍后使用

export class AppComponent { 
    public latitude: number; 
    public longitude: number; 

public constructor() 
{ 
     this.updateLocation(); 
     this.getWeather(this.latitude ,this.longitude); 
} 

private getDeviceLocation(): Promise<any> { 
     return new Promise((resolve, reject) => { 
      geolocation.enableLocationRequest().then(() => { 
       geolocation.getCurrentLocation({desiredAccuracy:3,updateDistance:10,timeout: 20000}).then(location => { 
        resolve(location); 

       }).catch(error => { 
        reject(error); 
       }); 
      }); 
     }); 
    } 

public updateLocation() { 
     this.getDeviceLocation().then(result => { 
// i am saving data here for later usage 
      this.latitude = result.latitude; 
      this.longitude = result.longitude; 
     }, error => { 
      console.error(error); 
     }); 
    } 

public getWeather(latitude:number,longitude:number){ 
// do stuff with lat and long 
} 
} 

,但我不能够通过经纬度的GetWeather method.It的价值当属undefined.What我做错了吗?我知道解决方法:通过从updateLocation中调用getWeather,其中这些值是可用的,并使这件事情起作用,但不知怎的,我觉得它不是一个合适的方式。提前感谢。

+0

的'的GetWeather()'函数将'更新位置之前进行发射()'方法有机会完成以便值不确定 – mast3rd3mon

回答

2

你认为“不合适的方式”实际上是合适的方式;您的this.updateLocation()函数是异步(Promise),因此下面的行(this.getWeather(this.latitude ,this.longitude))在this.latitudethis.longitude被初始化之前运行。

你要调用getWeather当那些被初始化,而这正是当无极updateLocation返回..

相关问题