我正在尝试将我的提供程序中找到的函数的结果获取到我的应用程序中的另一个页面。在本例中,结果是“城市名称”。当控制台注销响应时,我收到未定义的消息。
位置提供商
getLocation(cityname) {
this.options = {
enableHighAccuracy: false
};
return this.geolocation.getCurrentPosition(this.options).then((pos: Geoposition) => {
var geocoder = new google.maps.Geocoder;
var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
var cityname = results[1].formatted_address;
return cityname;
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}, (err: PositionError) => {
console.log("error : " + err.message);
})
}
另一页
import { LocationProvider } from './../../../../providers/location/location';
constructor(public navCtrl: NavController, public navParams: NavParams, public storage: Storage, private location: LocationProvider) {}
ionViewWillEnter() {
this.location.getLocation().then((data) =>{
console.log(data);
});
}
任何想法我做错了什么。目的是让城市名称在我的应用程序的其他部分重复使用
最佳答案
您的代码按照当前编写的方式没有意义:
- 您未在
getLocation
实现中使用变量cityname
- 签名
getLocation()
(在another page
中)和getLocation(cityname)
(在location 中)不匹配提供商
) - Google Maps API 允许您访问回调而不是 promise 。正如现在所写,您的方法不会返回任何内容。您必须将回调转换为 promise ,如 Promises With Google Maps Geocoder API 中所述。
我建议您通过清理一下来解决问题:
位置提供商
getLocation() { // remove cityname from the signature, it is not used anyway
this.options = {
enableHighAccuracy: false
};
return this.geolocation.getCurrentPosition(this.options).then((pos: Geoposition) => {
var geocoder = new google.maps.Geocoder;
var latlng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
return new Promise(function(resolve, reject) {
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
var cityname = results[1].formatted_address;
resolve(cityname)
} else {
reject('No results found');
}
} else {
reject('Geocoder failed due to: ' + status);
}
});
})
}
关于javascript - 从提供者函数获取值到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49529815/