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を直接呼び出すことによって、このことが機能しますが、何らかの形で、適切なway.Thanksではないと感じます。

+0

'getWeather()'関数は 'updateLocation(前に起動します)'メソッドは、偶然にしています値が定義されないように仕上げる – mast3rd3mon

答えて

2

「適切な方法ではない」と考えることは、実際には適切な方法です。 this.updateLocation()関数はasync(Promise)なので、this.latitudethis.longitudeが初期化される前に(this.getWeather(this.latitude ,this.longitude))以下の行が実行されます。

あなたがそれらが初期化されている場合getWeatherを起動することをお勧めします、と約束がupdateLocationに戻ったときにそれはまさに...

関連する問題