无法阅读财产'然后'未定义的AngularJS

时间:2017-02-08 06:24:45

标签: angularjs

我写了一个工厂方法:

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

在控制器中我写道:

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

但每当我运行时,我都会收到错误无法读取属性'然后'未定义的AngularJS

1 个答案:

答案 0 :(得分:1)

截至目前,您的工厂getLocation函数返回 undefined ,它未返回Promise,因此预计会出错。基本上你错放了return def.promise;声明。

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