0

I have written a factory method as :

myApp.factory('GetUserCurrentLocationService', ['$q', function ($q) {
            var GetUserCurrentLocationService = {};
            GetUserCurrentLocationService.getLocation = function () {
                var def = $q.defer();
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        def.resolve(position);
                        return def.promise;
                    });
                }
            }
            return GetUserCurrentLocationService;
        }
    ]);

and in controller I have written:

GetUserCurrentLocationService.getLocation().then(function(response){
        console.log(response);
    },function(error){
        console.log(error);
    })

but whenever i am running this I am getting error Cannot read property 'then' of undefined AngularJS

1 Answer 1

1

As of now your factory getLocation function returns undefined, it's not returning Promise, thus the error is expected. Basically you have misplaced the return def.promise; statement.

GetUserCurrentLocationService.getLocation = function () {
    var def = $q.defer();
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            def.resolve(position);
        });         
    } else {
        //Also reject if navigator.geolocation is undefined
        def.reject({});
    }
    //Function should return promised
    return def.promise;
}
Sign up to request clarification or add additional context in comments.

4 Comments

console.log(response); is still not showing anything
@lakshay, Are you getting any data then getCurrentPosition()?
i don't think so..........suddenly the navigator method has stop working.......it was working before
is there anything I can do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.