Javascript - 无法获取函数的值,未定义 [英] Javascript - Can't get the value of the function outside of it, getting undefined
本文介绍了Javascript - 无法获取函数的值,未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我愿意在它之外获得函数的价值;但是,我得到未定义
这里是以下代码:
I am willing to get the value of the function outside of it; however, I am getting undefined
here is the below code:
getCoords() {
let call = this.http.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + this.key).subscribe(data => {
let lat = data.json().results[0].geometry.location.lat;
let long = data.json().results[0].geometry.location.lng;
this.latLong = {
"lat": lat,
"long": long
};
//I can get it here
console.log('called >> ', this.latLong)
return this.latLong;
});
//this.latlong is undefined !
}
//if I call getCoords() here I get undefined too
推荐答案
如果订阅返回承诺
,返回
调用
,链 .then()
获取值 this.latLong
从返回.subscribe()
If subscribe returns a Promise
, return
call
, chain .then()
to get the value this.latLong
returned from within .subscribe()
getCoords() {
let url = 'https://maps.googleapis.com/maps/api/geocode/json?address='
+ address + '&key=' + this.key;
let call = new Promise((resolve, reject) => {
this.http.get(url).subscribe(data => {
let lat = data.json().results[0].geometry.location.lat;
let long = data.json().results[0].geometry.location.lng;
this.latLong = {
"lat": lat,
"long": long
};
//I can get it here
console.log('called >> ', this.latLong)
resolve(this.latLong);
});
});
return call.then(res => { console.log(res); return res })
//this.latlong is undefined !
}
getCoords()
.then(data => console.log(data))
.catch(err => console.log(err));
这篇关于Javascript - 无法获取函数的值,未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文