【问题标题】:Object property is not created inside a factory member function对象属性不是在工厂成员函数中创建的
【发布时间】:2015-02-23 13:07:18
【问题描述】:

我在 Angular.js 工厂中有一个对象:

angular.module('myapp')
        .factory('geoLocationService', function () {


            var geoLocationObj = {};

            var geocoder = new google.maps.Geocoder();

            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(_successFunction, _errorFunction);
            }
            function _successFunction(position) {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                var latlng = new google.maps.LatLng(lat, lng);
                geocoder.geocode({'latLng': latlng}, function (results, status) {

                    if (status === google.maps.GeocoderStatus.OK) {
                        if (results[2]) {
                            geoLocationObj.resultCity = results[2].formatted_address;
                            alert(geoLocationObj.resultCity);
                        } else {
                            alert("No results found");
                        }
                    } else {
                        alert("Geocoder failed due to: " + status);
                    }
                });
            }


            return geoLocationObj;


        });

这适用于alert(geoLocationObj.resultCity); 并在属性值中发出警报

但是

console.log(geoLocationObj);

不记录属性geoLocationObj.resultCity

我试图在我的控制器中的工厂外使用geoLocationObj.resultCity,但它不存在。

我的控制器中有:

.controller('IndexCtrl', function ($scope, geoLocationService) {

    var geoLocationService = geoLocationService;

    console.log(geoLocationService);

geoLocationService 是一个空对象

我无法弄清楚为什么会这样。 你能帮我解决这个问题吗?

【问题讨论】:

标签: javascript angularjs object


【解决方案1】:

您的代码中的问题是您的对象在回调 (_successFunction) 中进行了初始化,这意味着返回的对象仍然是空的,因为尚未调用 _successFunction。

您应该使用 $q 返回一个承诺并在您的控制器中调用 .then()。

angular.module('myapp')
    .factory('geoLocationService', ['$q', function ($q) {


        var geoLocationObj = {};
        var deferred = $q.defer();

        var geocoder = new google.maps.Geocoder();

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(_successFunction, _errorFunction);
        }
        function _successFunction(position) {
            var lat = position.coords.latitude;
            var lng = position.coords.longitude;
            var latlng = new google.maps.LatLng(lat, lng);
            geocoder.geocode({'latLng': latlng}, function (results, status) {

                if (status === google.maps.GeocoderStatus.OK) {
                    if (results[2]) {
                        deferred.resolve(results[2].formatted_address);
                        alert(geoLocationObj.resultCity);
                    } else {
                        alert("No results found");
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });
        }


        return deferred.promise;
    })];

在你的控制器中

.controller('IndexCtrl', function ($scope, geoLocationService) {
   geoLocationService.then(function(geoLocObj){
        console.log(geoLocObj); Here your object has been resolved
   });

【讨论】:

    【解决方案2】:

    你的工厂应该返回这样的东西

    angular.module('myapp')
    .factory('geoLocationService', function() {
    return{
        geoLocationObj:function(){
            var geocoder = new google.maps.Geocoder();
           if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(_successFunction, _errorFunction);
            }
            function _successFunction(position) {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                var latlng = new google.maps.LatLng(lat, lng);
                geocoder.geocode({'latLng': latlng}, function (results, status) {
    
                    if (status === google.maps.GeocoderStatus.OK) {
                        if (results[2]) {
                            geoLocationObj.resultCity = results[2].formatted_address;
                            alert(geoLocationObj.resultCity);
                        } else {
                            alert("No results found");
                        }
                    } else {
                        alert("Geocoder failed due to: " + status);
                    }
                });
            }
      return geoLocationObj 
    }
    }
    });
    

    你可以像这样调用你的控制器

    angular.module('myapp', [])
    .controller('IndexCtrl', function ($scope, geoLocationService) {
         var promise = geoLocationService.geoLocationObj()
             promise.then(function(success){
                      console.log("me "+success);
                     },function(error){
                      console.log("They eat all my candies :" +error)
                     })
    
    });
    

    你可以在Js bin这里玩

    PS。您需要包含您的谷歌地图库

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多