我愿意在它之外获得函数的价值;但是,我得到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
答案 0 :(得分:2)
如果订阅返回Promise
,return
call
,则链.then()
以获取this.latLong
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));
答案 1 :(得分:0)
当然,因为http.get
是异步方式,所以回调函数(subscribe
)会在行this.latlong
将调用后调用,所以在那个时间{ {1}}是this.latlong
。