2017-04-01 31 views
1

我定義了public currentLocation : {lat: number, lng: number};,並且我在this.geolocation方法console.log(this.currentLocation)中獲得了currentLocation的值。但在console.log(this.currentLocation)這塊以外,我沒有定義。我怎樣才能在全局變量中獲得價值?Ionic serve在此打字稿代碼中顯示此錯誤Ionic2

export class DetailsPage { 

    typeDetails: {}; 

    public currentLocation : {lat: number, lng: number}; 

    posOptions = { 
    enableHighAccuracy: true, 
    timeout: 20000, 
    maximumAge: 0 
}; 



    constructor(public navCtrl: NavController, 
      public navParams: NavParams, 
      private typeApi : TypeApi, 
      public geolocation : Geolocation) {} 


    ionViewDidLoad() { 
    let baseUrl ='https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2150756,72.8880545&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg'; 
    this.geolocation.getCurrentPosition().then((resp) => { 

     this.currentLocation ={ 
      lat :resp.coords.latitude, 
      lng :resp.coords.longitude 

     }; 

console.log(this.currentLocation); 


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


    console.log(this.currentLocation); 



console.log('ionViewDidLoad DetailsPage'); 

    //this.typeDetails = this.typeApi.getTypeDetails(); 
    //console.log(this.typeDetails); 

    this.typeApi.getTypeDetails().then(data => { 
    this.typeDetails = data; 
    console.log(this.typeDetails); 
    }); 
    } 


} 

回答

1

因此,它是一個promise你有如圖所示below.Due到async性質使用console.log(this.currentLocation);resolve方法裏面,你不能登錄它promise外.B'cose你不知道哪一刻它會有價值的。

this.geolocation.getCurrentPosition().then((resp) => { 

     this.currentLocation ={ 
      lat :resp.coords.latitude, 
      lng :resp.coords.longitude 

     }; 

    console.log(this.currentLocation);//here you have to use log method 

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