TypeError:无法读取未定义的属性'then'

时间:2014-07-16 18:34:45

标签: javascript angularjs promise

loginService.islogged() 

上面的函数返回一个字符串,如"失败"。 但是,当我尝试运行然后对它进行操作时,它将返回错误

TypeError: Cannot read property 'then' of undefined

,光标在connected之后和.then之前指示。

以下是完整功能:

var connected=loginService.islogged();
alert(connected);
connected.then(function(msg){
    alert("connected value is "+connected);
    alert("msg.data value is "+msg.data);
    if(!msg.data.account_session || loginService.islogged()=="failed")       
        $location.path('/login');
});

更新

这是islogged()函数

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
        return $checkSessionServer;
    });
}

我确信$checkSessionServer会导致"失败"串。没什么。

2 个答案:

答案 0 :(得分:109)

您需要将您的承诺退回到调用函数。

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}

答案 1 :(得分:0)

TypeError:使用AngularJS调用Django服务时,无法读取未定义的属性'then'。

如果您正在调用Python服务,代码将如下所示:

this.updateTalentSupplier=function(supplierObj){
  var promise = $http({
    method: 'POST',
      url: bbConfig.BWS+'updateTalentSupplier/',
      data:supplierObj,
      withCredentials: false,
      contentType:'application/json',
      dataType:'json'
    });
    return promise; //Promise is returned 
}

我们使用MongoDB作为数据库(我知道这没关系。但如果有人用MongoDB + Python(Django)+ AngularJS搜索,结果应该会出现。

相关问题