在subscribe()之后获取返回变量的值

时间:2017-05-14 18:16:50

标签: javascript angular

我使用下面的代码进行异步调用,我想知道data函数中生成的getData()的值,但是我得到undefined,因为调用是尚未解决。有什么方法可以解决它吗?

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

3 个答案:

答案 0 :(得分:1)

嗯,这是你可以做的解决方法,只需将数据推入数组,然后你可以在其他函数中检索它。

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

答案 1 :(得分:0)

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

然后你需要订阅以获得一个值。

secondMethod(item){
    this.getData(item.address).subscribe(data => {
        console.log(data);
    });
}

答案 2 :(得分:0)

以下是您如何将这项工作牢记为异步。

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'];
}