【问题标题】:AngularJs cannot read property 'then' of undefinedAngularJs 无法读取未定义的属性“then”
【发布时间】:2016-02-11 20:08:59
【问题描述】:

我有一个包含此功能的 authenticationService:

//this.userApi = Restangular.service('api/sessions');

login(user) {
    let that = this;

    this.userApi.post(user).then(function(user) {
        that.session.create(user.sessionId, user.userId, user.username);
        return user;
    });
}

在我的控制器中:

login() {
    this.authService
        .login(that.user)
        .then(function(user) {
            $scope.setCurrentUser(user);

        },
        function(result) {
            console.log('fail', result.status);
        });
}

我不明白为什么我在这一行得到“无法读取未定义的属性 'then'”:that.authService.login(that.user).then(function (user) ...

【问题讨论】:

  • that.authService.login 显然返回未定义。 (你的代码不会让它返回任何东西)
  • 根据我的调试器,它不会返回 undefined。
  • 再次阅读错误信息。指向that.authService.login().then( 行的“无法读取未定义的'then' 属性”很明显它返回未定义,因为then 未在undefined 上定义。
  • 哦,它是未定义的。但我不明白为什么?
  • 因为您在第一个 sn-p 中没有从 login(user) { 返回任何东西。如果在这种情况下不返回任何内容,则返回 undefined

标签: angularjs restangular


【解决方案1】:

在您的第一个 sn-p 中,您需要返回承诺,以便您可以在另一个 sn-p 中继续该链。

//this.userApi = Restangular.service('api/sessions');

login(user) {
    let that = this;

    return this.userApi.post(user).then(function(user) {
        that.session.create(user.sessionId, user.userId, user.username);
        return user;
    });
}

【讨论】:

  • 很接近 kevin :D 你比我快 3 秒,我会支持你的回答
  • 无论如何都很好的答案;)
  • 谢谢你们,我接受了这个答案,因为我是通过他的乐于助人的 cmets 找到的。
【解决方案2】:

你应该试试这个:

//this.userApi = Restangular.service('api/sessions');

login(user) {
    let that = this;

   return this.userApi.post(user).then(function(user) {
        that.session.create(user.sessionId, user.userId, user.username);
        return user;
    });
}

【讨论】:

    猜你喜欢
    • 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
    相关资源
    最近更新 更多