Reputation: 1204
I doing an Async call using the below code, I want to know the value of data
that is generated inside the getData()
function however, I am getting undefined
because the call is not resolved yet. Is there any way to sort it out?
getData(address){
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&key='+this.key;
let call = this.http.get(url).subscribe(data =>{
let data = data.json()
return data;
});
}
//this is undefined because it does not know if the call was finished or not
console.log(this.latlong)
secondMethod(item){
//this is also undefined
this.getData(item.address)
}
Upvotes: 2
Views: 793
Reputation: 1823
Well, here is what you can do to solve it, simply push the data inside an array, then you may retrieve it in other functions.
getData(address){
let array = [];
let url = 'https://maps.googleapis.com/maps/api/geocode/json? address='+address+'&key='+this.key;
let call = this.http.get(url).subscribe(data =>{
let data = data.json()
array.push(data);
});
return array;
}
secondMethod(item){
//now you'll be able to retrieve it !
this.getData(item.address)
}
Upvotes: 1
Reputation: 22246
Here's how you could make that work keeping in mind async.
getData(address, callback){
let url = 'https://maps.googleapis.com/maps/api/geocode/json?
address='+address+'&key='+this.key;
let call = this.http.get(url).subscribe(callback);
}
secondMethod(item){
this.getData(item.address, this.thirdMethod.bind(this))
}
thirdMethod(data) {
let data = data.json()
// do stuff
this.something = data['something'];
}
Upvotes: 0
Reputation: 1038
getData(address){
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&key='+this.key;
return this.http.get(url).map(data => data.json());
})
Then you need to subscribe to get a value.
secondMethod(item){
this.getData(item.address).subscribe(data => {
console.log(data);
});
}
Upvotes: 0