我愿意在函数之外获取函数的值;但是,我得到 undefined
这是下面的代码:
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
最佳答案
如果订阅返回一个Promise
,return
call
,链.then()
来获取值this.latLong
从 .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 - 无法获取函数外部的值,变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965421/