javascript - 对象属性不是在工厂成员函数内创建的

标签 javascript angularjs object

我在 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

我试图在 Controller 的工厂外部使用geoLocationObj.resultCity,但它不在那里。

我的 Controller 中有:

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

    var geoLocationService = geoLocationService;

    console.log(geoLocationService);

geoLocationService 是一个空对象

我不明白为什么会发生这种情况。 你能帮我解决这个问题吗?

最佳答案

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

您应该使用 $q 返回一个 Promise 并在 Controller 中调用 .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 中

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

关于javascript - 对象属性不是在工厂成员函数内创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28674549/

相关文章:

javascript - 谷歌图表 - GeoChart "Incompatible data table: Error: Unknown address type."

c# - 为什么 GC.GetTotalMemory() 和 CLR Profiler 数字之间存在巨大差异?

java - 从两个自定义对象列表中删除公共(public)元素

c++ - 有没有更好的方法来编写这个 C++ 代码

javascript - 使用 UI Utils 进行 Angular 表单验证

javascript - 将 Meteor 与 Adob​​e Flash CreateJS 工具包一起使用

javascript - 立即函数与另一个函数调用 Javascript

javascript - 在responseError方法中访问响应头

angularjs - Ionic ion-slide-box Update/Slide with ng-repeat

javascript - Angular JS : input[radio] doesn't work