CiscoKidx CiscoKidx - 3 months ago 9
AngularJS Question

AngularJS controller logic does not execute

I have a call to an API that verifies the existence of a user. If a user is found it will send 200, otherwise it will send 404. Below is my AngularJS controller. For some reason, via developer tools I see the 404 return from my API but this controller does not follow the programmed logic. It does nothing. When a 200 is received it performs as expected. Any thoughts?

var params = $stateParams.resetToken;
var foundUser;

$http.get('/api/user/' + params, {

})
.then(function onSuccess (res) {
foundUser = true;
})
.then(function onError(res) {
if (res.status === 404) {
foundUser = false;
$location.path('/lost');
} else {
console.log(err);
}
});

Answer

Use .catch to process status 404 responses.

  var params = $stateParams.resetToken;
  var foundUser;

  $http.get('/api/user/' + params, {

  })
  .then(function onSuccess (res) {
      foundUser = true;
  })
  //.then(function onError(res) {
  //USE catch to handle errors
  .catch(function onError(res) (
      if (res.status === 404) {
        foundUser = false;
        $location.path('/lost');
      } else {
        console.log(err);
      }
  });
Comments