Ammar Alnaimat Ammar Alnaimat - 4 months ago 15
AngularJS Question

Angular factory keep returned undefined

My Angular factory keep return unddefined, below are two snippets that I am trying.

This is my geoLocationService.js

myApp.factory('geoLocationService', function () {

return {
getMyGeolocation: function () {

var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0 };

var x = navigator.geolocation.getCurrentPosition(function success(pos) {
return pos.coords;
}, function error(err) {
console.log(err);
}, options);
}
}
});


and this is my controller.js

myApp.controller('homeCtrl', function($scope, geoLocationService){

$scope.shareThePost = function(){
geoLocationService.getMyGeolocation().then(function(data){
console.log(data)
});
}
});

Answer

You are not returning the promise. Every .then() relies on a promise being returned.

Add:

return x;

To the end of the getMyGeolocation function. And better yet, since you're not using the x anywhere else - you can return straight away:

return navigator.geolocation.getCurrentPosition(....)

EDIT: Looks like the getCurrentPosition does not return a promise, so you can't chain .then() on it. Instead, you need to wrap it with promise yourself to achieve what you want:

myApp.factory('geoLocationService', function ($q) {

return {
    getMyGeolocation: function  () {

        var deferred = $q.defer();

        var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0 };

        navigator.geolocation.getCurrentPosition(function success(pos) {
            deferred.resolve(pos.coords);
        }, function error(err) {
            console.log(err);
            deferred.reject(err);
        }, options);

        return deferred.promise;
    }
}
});
Comments