0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure exactly what I was looking at, but it's good to know it was incorrect. It's been confusing learning the framework because I feel like most of the questions I see people ask are before the .then() syntax was introduced. But after seeing your answer the difference between the two makes a lot more sense.
Angular DID deprecate the .success()/ .error() callbacks for $http, but not interceptors.

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.