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

AngularJs cannot read property 'then' of undefined

我有一个包含此功能的身份验证服务:

//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) ...

你应该试试这个:

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

在您的第一个代码段中,您需要 return 承诺,以便您可以在其他代码段中继续链。

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