1

Having a UserService with the following code:

this.result = function(credentials)
    {
        $http.post('http://localhost:8080/user/login', credentials).then(function (status) {
            return status;
        });
    };

And a LoginController with the following code:

$scope.doLogin = function()
    {
        var result = UserService.result($scope.credentials);
        alert(result);
    };

Why does the alert window popup before the POST is done/shown in firebug console, giving me an undefined message instead of a HTTP status code?

4 Answers 4

2

This is because $http is an async operation. And so, it immediately returns a promise and then executes the handler at a later time. return status; returns the value to whoever handles the result.

In your case, this.result function doesn't return anything - it just executes the $http call, and so the result is undefined. Immediately afterwards the program executes alert(result).

The correct way is to follow through with promises until the end, and assign the value in the promise handler.

this.result = function(credentials)
{
    return  // return the promise
       $http.post('http://localhost:8080/user/login', credentials);
}

Then, in the controller, handle the promise:

$scope.doLogin = function(){
    UserService.result($scope.credentials)
       .then(function(result){
          alert(result);
       });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Because $http is asynchronous. The alert would need to be in a callback function or in the promise itself. For example:

// Service
this.result = function(credentials) {
    return $http.post('http://localhost:8080/user/login', credentials);
};

// Controller
UserService.result($scope.credentials).then(function (status) {
    alert(status);
});

Comments

1

Because it's asynchronous. When you call UserService.result it will send the request and then return. Then you immediately do the alert.

Instead you should do the alert when the request completes, by returning the promise and putting your alert in .then().

Comments

1

Your function returns undefined (because it's not set to return anything). Don't be confused by what you return in the callback function - it never goes "out" to the original function.

The easiest fix is to return the whole $http call object (which returns a promise), and do the then() part in the controller.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.