【问题标题】:creating an angular service with Google map API service call back function使用 Google 地图 API 服务回调函数创建角度服务
【发布时间】:2013-09-27 07:44:18
【问题描述】:

我正在尝试创建一个使用谷歌地图地理编码器的角度服务,但是我发现来自谷歌的回调是在执行服务函数之后执行的。

控制器

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);
                            }
                    });
            };
    });

问题是,控制器中的console.log(result) 输出未定义,服务中的console.log(results) 在调用函数后从google 获取结果。也就是回调函数没有及时返回结果。

有没有办法解决这个问题? 谢谢。

【问题讨论】:

  • roland 和 Chandermani 回答了我的问题。由于 Chandermani 的回复提供了两种方法,因此被接受。谢谢大家

标签: angularjs google-maps-api-3


【解决方案1】:

回调是处理网络\网络调用的异步性质的方法。您需要将geocode 方法的实现更改为任一

  • 在收到响应时调用回调函数。
  • 返回一个可以在调用函数中使用then函数处理的promise。

我发现这篇博文详细介绍了这两种方法http://markdalgleish.com/2013/06/using-promises-in-angularjs-views/

【讨论】:

    【解决方案2】:

    正如 Chandermani 指出的,您需要为您的方法提供回调:

    app.service('geocoder',function() {
                this.geocode=function(address, outerCallback) {
                        var geocoder = new google.maps.Geocoder();
                        geocoder.geocode( { 'address': address}, function(results, status) {
                                console.log(results);
                                if (status == google.maps.GeocoderStatus.OK) {
                                        outerCallback({success: true, err: null, results: results});
                                } else {
                                        outerCallback({success:false, err: new Error('Geocode was not successful for the following reason: ' + status), results: null});
                                }
                        });
                };
        });
    

    在您的控制器中:

    app.controller( 'AppCtrl',['geocoder',function AppCtrl (geocoder) {
       var result=geocoder.geocode('greek', function(callbackResult) {
          console.log(callbackResult); //{success: true, err: undefined, results: {...} or {success:false, err: Error object, results: undefined}
       });
    
    });
    

    如果这可行,那么您可以重构代码以使用promise

    希望这会有所帮助,

    R.

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 2021-09-30
      • 2021-08-25
      • 2021-01-11
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 2016-12-30
      • 1970-01-01
      相关资源
      最近更新 更多