【问题标题】:Angularjs:TypeError: Cannot read property 'then' of undefinedAngularjs:TypeError:无法读取未定义的属性“then”
【发布时间】:2014-08-25 16:03:53
【问题描述】:

在一个 angularjs 项目中,我想获取登录的用户数据并以 html 形式使用这些数据。

为此,我有一个sessionService.js 向服务器发送请求并从中获取响应。我在sessionService.js 中有以下代码:

          login: function(email, password) {
               $http.post('/api/sessions', {user: {email: email, password: password} })
                    .then(function(response) {
                        service.currentUser = response.data.user;
                        if (service.isAuthenticated()) {
                            //$location.path(response.data.redirect);
                            $location.path('/record');
                        }
                    });
            },
           requestCurrentUser: function() {
                if (service.isAuthenticated()) {
                    alaki = $q.when(service.currentUser);
                    console.log("1"+JSON.stringify(alaki));
                    return alaki;
                } else {
                    return $http.get('/api/users').then(function(response) {
                        service.currentUser = response.data.user;
                        console.log("2"+JSON.stringify(service.currentUser));
                        return service.currentUser;
                    });
                }
            },

            isAuthenticated: function(){
                return !!service.currentUser;
            }

当我第一次调用 requestCurrentUser 时,if (service.isAuthenticated()) 正在运行,我在 chrome 控制台中遇到以下错误:

TypeError: Cannot read property 'then' of undefined

如果我再次刷新页面,这次else 语句及以上错误不会发生。我没有任何想法来解决这个问题。我该如何解决这个错误?

【问题讨论】:

  • 看来错误可能是由于alaki = $q.when(service.currentUser);这一行,因为传递的值为null。

标签: angularjs


【解决方案1】:

由于 $http 承诺被返回,您需要在$http.post() 之前添加return。所以,新代码看起来像 - return $http.post('/api/sessions'..)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 2019-08-19
    • 2016-10-23
    • 2014-09-07
    • 2015-09-08
    • 2018-01-12
    相关资源
    最近更新 更多