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?
error(or whatever it's called in Angular)? Does the error function run?then. A success function, and a failure function. If you don't pass a failure function, it won't be run. The first function only runs on a success, and an HTTP error code of 400+ isn't a success. If your code is setting an HTTP code you need to take that into account. Try putting in the error handler in the login code.