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返回..

相關問題