【问题标题】:Cannot read property 'then' of undefined AngularJS无法读取未定义 AngularJS 的属性“then”
【发布时间】:2017-02-08 14:33:53
【问题描述】:

我写了一个工厂方法:

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

但是每当我运行它时,我都会收到错误 Cannot read property 'then' of undefined AngularJS

【问题讨论】:

    标签: angularjs


    【解决方案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;
    }
    

    【讨论】:

    • console.log(response); 仍然没有显示任何内容
    • @lakshay,你有没有得到任何数据然后getCurrentPosition()
    • 我不这么认为............导航器方法突然停止工作.......它之前工作过
    • 有什么我可以做的吗?
    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2016-06-18
    • 1970-01-01
    • 2015-03-28
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多