Reputation: 855
in this typescript code i define public currentLocation : {lat: number, lng: number};
and i get value of currentLocation
inside this.geolocation
method in console.log(this.currentLocation)
. but outside of this block in console.log(this.currentLocation)
i got undefine. How can i get value in global variable?
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);
});
}
}
Upvotes: 1
Views: 109
Reputation: 65860
Hence it is a promise
you have to use console.log(this.currentLocation);
inside the resolve
method as shown below.Due to the async
nature, you cannot log it outside the promise
.B'cose you don't know which moment it'll have a value.
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);
});
Upvotes: 1