J. West J. West - 13 days ago 5
AngularJS Question

Angular response.status not running

From what I've researched, it looks like the $http interceptor is deprecated, so I'm not sure what the current best practice for this is. I'm returning a 409 status if a user attempts to register with a username that is already taken, and I'm attempting to handle it client-side with the following:

$http.post('/register-user',payloadCredentials,config).then(function(response) {
if (response.status == 409) {
$scope.errorResponseUserName = "Username already exists.";
$scope.error = true;
clearPasswords();
clearUsername();
} else {
$rootScope.authenticated = true;
$location.path("/")
}
});


I'm still new to Angular, so I'm not sure why this function seemingly doesn't run if a status code interrupts it. The other questions on SO I've seen apply to the past Angular style of using the
.success()
and
.error()
callbacks, but I haven't found any situations using the newer
.then()
syntax. Any ideas are appreciated.

Answer

As for all promises, then() expects two callbacks; one called when the promise is resolved (i.e. in case of success), one when it's rejected (i.e. in case of error). A 409 status is an error. So you (most probably) need

$http.post('/register-user',payloadCredentials,config).then(function(response) {
    $rootScope.authenticated = true;
    $location.path("/")
}, function(response) {
    $scope.errorResponseUserName = "Username already exists.";
    $scope.error = true;
    clearPasswords();
    clearUsername();
});

Or you could also use catch():

$http.post('/register-user',payloadCredentials,config).then(function(response) {
    $rootScope.authenticated = true;
    $location.path("/")
}).catch(function(response) {
    $scope.errorResponseUserName = "Username already exists.";
    $scope.error = true;
    clearPasswords();
    clearUsername();
});

I'm not sure where you get that interceptors were deprecated. There is no deprecation mention in their documentation. But anyway, interceptors don't look like the appropriate tool for handling this specific situation.