Tasos Tasos - 1 month ago 5
AngularJS Question

Get $http response error status on AngularJS

I follow an online course in AngularJS and I am on the first steps of learning it.

I am trying to call an API after a form submission and based on the API response, show and hide some data.

What I try to do first is to check the status response in case it returns 500 error for invalid API call. However, it seems I cannot do it.

Part of my service file:

service.getMenuItem = function (shortName) {

return $http.get(ApiPath + '/menu_items/' + shortName + '.json')
.then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
return response.status;
})
};


And on my controller:

SignupController.$inject = ['MenuService'];
function SignupController(MenuService) {
var signupCtrl = this;

signupCtrl.submit = function () {
signupCtrl.response = MenuService.getMenuItem(signupCtrl.user.favouritedish);
if ( signupCtrl.response == 500 ) {
signupCtrl.dishError = true;
}
};
}


If I don't have any error on the $http call, everything work as it should. However, with the 500 error, it seems that it doesn't. I tried to log the
signupCtrl.response
on my controller and the
value: 500
is there. But the if cannot be validated.

Version 1.5.8 on AngularJS

Answer

Call a service function with .then() chaining method.

SignupController.$inject = ['MenuService'];

    function SignupController(MenuService) {
      var signupCtrl = this;

      signupCtrl.submit = function() {

        MenuService.getMenuItem(signupCtrl.user.favouritedish)
          .then(function(result) {
            console.log(result.data)
          }, function(error) {
            console.log(error.data)
          })
      };
    }
Comments