Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch a 401 (or other status error) in an angular service call?

Tags:

rest

angularjs

Using $http I can catch errors like 401 easily:

$http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'}).
success(function(data, status, headers, config) {
    $scope.posts = data;
}).
error(function(data, status, headers, config) {
    if(status == 401)
    {
        alert('not auth.');
    }
    $scope.posts = {};
});

But how can I do something similar when using services instead. This is how my current service looks:

myModule.factory('Post', function($resource){
    return $resource('http://localhost/Blog/posts/index.json', {}, {
          index: {method:'GET', params:{}, isArray:true}
    });
});

(Yes, I'm just learning angular).

SOLUTION (thanks to Nitish Kumar and all the contributors)

In the Post controller I was calling the service like this:

function PhoneListCtrl($scope, Post) {
    $scope.posts = Post.query();
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];

As suggested by the selected answer, now I'm calling it like this and it works:

function PhoneListCtrl($scope, Post) {
    Post.query({},
    //When it works
    function(data){
        $scope.posts = data;
    },
    //When it fails
    function(error){
        alert(error.status);
  });
}
//PhoneListCtrl.$inject = ['$scope', 'Post'];
like image 802
Lay González Avatar asked Sep 24 '13 19:09

Lay González


3 Answers

in controller call Post like .

Post.index({}, 
          function success(data) { 
              $scope.posts = data; 
          },
         function err(error) {
           if(error.status == 401)
           {
             alert('not auth.');
           }
           $scope.posts = {};
         }
  );
like image 155
Nitish Kumar Avatar answered Nov 13 '22 00:11

Nitish Kumar


Resources return promises just like http. Simply hook into the error resolution:

Post.get(...).then(function(){
  //successful things happen here
}, function(){
  //errorful things happen here
});

AngularJS Failed Resource GET

like image 1
Fourth Avatar answered Nov 13 '22 00:11

Fourth


$http is a service just like $resource is a service.

myModule.factory('Post', function($resource){
  return $http({method: 'GET', url: 'http://localhost/Blog/posts/index.json'});
});

This will return the promise. You can also use a promise inside your factory and chain that so your factory (service) does all of the error handling for you.

like image 1
Jonathan Rowny Avatar answered Nov 13 '22 00:11

Jonathan Rowny