gpt4 book ai didi

javascript - subscribe() 后获取返回变量的值

转载 作者:行者123 更新时间:2023-11-29 23:46:13 25 4
gpt4 key购买 nike

我使用下面的代码进行异步调用,我想知道在 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)
}

最佳答案

好吧,这是您可以解决的方法,只需将数据放入数组中,然后您就可以在其他函数中检索它。

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

关于javascript - subscribe() 后获取返回变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43967354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com