首页 文章

如何将数据值从服务提供者返回到组件| Angular 4 |离子的

提问于
浏览
1

我想从服务提供商文件返回地理位置纬度和经度值 .

代码如下所示 . 组件或页面'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);
   });

  }

我得到的结果是未定义的 . 我是打字稿的新手,抱歉这个愚蠢的问题 . 谢谢大家

3 回答

  • 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);
       });
    
      }
    

    在您的组件中,调用 Promise.then() 以访问从promise返回的 resp

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

    你应该在调用this.geolocation.getCurrentPosition之前添加return,因为它是一个promise .

    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

    Add this code your service '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);
          });
    });
    
      }
    

    And your component file:

    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);
          });
      }
    

相关问题