2017-10-25 1 views
0

サービスプロバイダファイルからジオロケーションの緯度と経度の値を戻したいとします。サービスプロバイダからコンポーネントにデータ値を戻す方法| | Ionic

コードは次のとおりです。 コンポーネントまたは未定義として結果を取得するページ 'home.ts'

import { WeatherProvider } from '../../providers/weather/weather'; 

constructor(public navCtrl: NavController,private weatherProvider: WeatherProvider) { 
    console.log(this.weatherProvider.getGeoLocation()+'kkk'); 
    } 

プロバイダファイル 'weather.ts'

import { Geolocation } from '@ionic-native/geolocation'; 
.... 
.... 
constructor(public http: Http, private geolocation: Geolocation) { } 
getGeoLocation() { 
    this.geolocation.getCurrentPosition().then((resp) => { 
    // console.log(resp.coords.latitude) 
    // console.log(resp.coords.longitude) 
    return resp; 

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

    } 

I'am。私はタイトスクリプトの初心者です、愚かな質問を申し訳ありません。おかげさまで

答えて

1

コンポーネントのサービスとチェーンから約束を返す必要があります。あなたのコンポーネントで

getGeoLocation() { 
    //return the promise 
    return this.geolocation.getCurrentPosition().then((resp) => { 
    // console.log(resp.coords.latitude) 
    // console.log(resp.coords.longitude) 
    return resp; 

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

    } 

respが、それは約束ですので、あなたは、コールthis.geolocation.getCurrentPosition前にリターンを追加する必要があります約束、

this.weatherProvider.getGeoLocation() 
    then(loc => { 
     console.log(loc); 
    }); 
+0

感謝の男は、私がチェックし、更新します – Rijo

+0

ワンなぜ我々が約束したいのか疑問に思う。どのようにtypescript – Rijo

+0

で働いているのか、TypeScriptはJavaScriptのための透明性であり、JavaScriptは無条件です。 –

0

から返さアクセスするためにPromise.then()を呼び出します。

constructor(public http: Http, private geolocation: Geolocation) { } 
getGeoLocation() { 
    return this.geolocation.getCurrentPosition().then((resp) => { 
    // console.log(resp.coords.latitude) 
    // console.log(resp.coords.longitude) 
     return resp; 

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

返信ありがとうございました。 – Rijo

0

このコードを追加します。あなたのサービス 'weather.ts'

import { Geolocation } from '@ionic-native/geolocation'; 
.... 
.... 
constructor(public http: Http, private geolocation: Geolocation) { } 
getGeoLocation() { 
    return new Promise((resolve, reject) => { 
     this.geolocation.getCurrentPosition() 
     .then((resp) => { 
      resolve(resp.json()); 
     }).catch((error) => { 
      console.log('Error getting location', error); 
      reject(error); 
     }); 
}); 

    } 

そして、あなたのコンポーネントファイル:

import { WeatherProvider } from '../../providers/weather/weather'; 

constructor(public navCtrl: NavController,private weatherProvider: WeatherProvider){ 
    this.weatherProvider.getGeoLocation() 
     .then((res) => { 
      console.log(res); 
     }) 
     .catch((err) => { 
      console.log(err); 
     }); 
    } 
+0

エラーresp.json() – Rijo

関連する問題