AngularJs cannot read property 'then' of undefined

Issue

I have an authenticationService which contains this function:

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

And in my controller:

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

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

I don’t understand why I get ‘Cannot read property ‘then’ of undefined’ on this line: that.authService.login(that.user).then(function (user) ...

Solution

In your first snippet, you need to return the promise so that you can continue the chain in your other snippet.

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

Answered By – Kevin B

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.