I am trying to push the value get from http
request to a local declare variable userLat & userLng
and access the variables from another function but getting undefined
as result. The userLat & userLng
was successfully retrieved. Tried using return this.userLat & this.userLng
but failed, please point out if I make any mistake.
Previously work with using promised. Had alot of headache. Is there a simpler way to get the data?
Any help and suggestions are appreciated. Thanks in advance:)
map.ts
export class GoogleMapsProvider {
userLat:any;
userLng:any;
constructor(
public http: Http,
) {
}
load(){
this.http.post()
.map(res => res.json())
.subscribe(data =>
{
this.userDetails = data[0];
this.userLat = this.userDetails.ListerLat;
this.userLng = this.userDetails.ListerLng;
console.log(this.userLat); // successfully return userLat
console.log(this.userLng); // successfully return userLng
//tried return this.userLat & this.userLng
}
}
calculate(locations) {
console.log(this.userLat); //returned undefined
console.log(this.userLng); //returned undefined
let usersLocation = {
lat: this.userLat,
lng: this.userLng
};
}
using promise
load(){
if(this.data){
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('../example.json').map(res => res.json()).subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}