简体   繁体   中英

Object property is not created inside a factory member function

I have an object inside an Angular.js factory:

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;


        });

This works alert(geoLocationObj.resultCity); and alerts in property value

But

console.log(geoLocationObj);

does not log the propety geoLocationObj.resultCity

I am trying to use geoLocationObj.resultCity outside the Factory in my controller but it is not there.

I have in my controller:

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

    var geoLocationService = geoLocationService;

    console.log(geoLocationService);

geoLocationService is an empty Object

I cannot figure out why this is happening. Can you help me with this?

The problem in your code is that your object is initialize in the callback (_successFunction) that means that the returned object is still empty because the _successFunction hasn't been called.

You should return a promise using $q and call .then() in your controller.

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

And in your controller

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

Your factory should return something like this

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

You can call in your controller like this

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

});

You can play it here in Js bin

PS. You need to include your google map libs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM