我正在尝试创建一个使用谷歌地图地理编码器的 angular.service ,但是我发现谷歌的回调是在服务函数执行后执行的。
Controller
app.controller( 'AppCtrl',['geocoder',function AppCtrl (geocoder) {
var result=geocoder.geocode('greek');
console.log(result);
});
服务
app.service('geocoder',function() {
this.geocode=function(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
return results;
} else {
return ('Geocode was not successful for the following reason: ' + status);
}
});
};
});
问题是, Controller 中的console.log(result)输出未定义,而服务中的console.log(results)在调用该函数后从google返回结果。即回调函数没有及时返回结果。
有办法解决这个问题吗? 谢谢。
最佳答案
回调是处理网络\Web 调用的异步性质的方法。您需要将 geocode
方法的实现更改为
- 当收到响应时调用回调函数。
- 返回一个可在调用函数中使用
then
函数处理的 Promise。
我发现这篇博文详细介绍了这两种方法 http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/
关于angularjs - 使用 Google map API 服务回调函数创建 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18941853/