I am currently working on building a login flow in AngularJS 1.3. My problem is that the promise return from an $http call is not resolving the code inside of its '.then'.
I am working to handle error messages that come back from the server, specifically to handle any 401 errors which are returned when the user has input the wrong username or password. However, when a 401 is returned, the .then never resolves itself and the code within them never runs.
The relevant code is as follows:
The controller for the login form as a login function on its scope, as follows:
$scope.login = function() {
$scope.authError = null;
// Try to login
var promise = session.login($scope.user);
promise.then(function(loggedIn) {
// THIS CODE NEVER RUNS
if ( !loggedIn ) {
$scope.authError = localizedMessages.get('login.error.invalidCredentials');
}
}, function(x) {
$scope.authError = localizedMessages.get('login.error.serverError', { exception: x });
});
};
I have a session factory that takes care of the login and other session based needs. The code for login is:
login: function(credentials) {
var $http = $injector.get('$http');
var url = ENV.apiEndpoint + "/sessions";
var newSession = $http.post(url, credentials);
return newSession.then(function(data) {
session.set(data.token);
//THIS CODE ONLY RUNS ON A SUCCESS RESPONSE
if(session.isAuthenticated()) {
closeLoginModal(true);
}
return session.isAuthenticated();
});
}
I have placed comments in the code where the problem is. I am at a loss as to why this code isn't working. From my understanding of promises, then 'then' should resolve no matter what the response was, success of error.
I have an interceptor running, but I have tried disabling it with no luck to the end result.
Am I missing something?
If your login (server-side) returns an HTTP error code, like a 401, this should resolve to an error, e.g., the second function passed to then
. If you don't pass one it should bomb out; that's why your higher-level error function gets called.