Javascript 在subscribe()之后获取返回变量的值
我使用下面的代码进行异步调用,我想知道在Javascript 在subscribe()之后获取返回变量的值,javascript,angular,Javascript,Angular,我使用下面的代码进行异步调用,我想知道在getData()函数中生成的data的值,但是,我得到了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 =>
getData()
函数中生成的data
的值,但是,我得到了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)
}
然后您需要订阅以获得一个值
secondMethod(item){
this.getData(item.address).subscribe(data => {
console.log(data);
});
}
下面是如何让这项工作保持异步
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'];
}
好的,这里是你可以做什么来解决它,只需将数据推送到一个数组中,然后你可以在其他函数中检索它
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)
}
将
console.log(data)
放在subscribe()
内部。在subscribe
内部,它打印数据,问题在subscribe
外部,正如您已经说过的,“我正在进行异步调用…”,因此您不能假设请求在subscribe
外部得到解决。外部的语句通常在..之前执行。。顺便说一句,你想实现什么?另外,看看带有typescript的异步代码,因为它可以使它更简单readable@developer033应该有一种方法可以获得该值,我需要从Google Maps API中获取纬度和经度,该API在getData()中生成,并在secondMethod()中获取数据
console.log()
inside second method printsundefined
这说明了如何进行异步的概念-如果有一个小的语法错误,我希望您找到并修复它,或者至少报告错误消息,并且此代码的工作取决于您的其他代码的工作。
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)
}