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


using $http can catch errors 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 similar when using services instead. how 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 learning angular).

solution (thanks nitish kumar , contributors)

in post controller calling service this:

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

as suggested selected answer, i'm calling , works:

function phonelistctrl($scope, post) {     post.query({},     //when works     function(data){         $scope.posts = data;     },     //when fails     function(error){         alert(error.status);   }); } //phonelistctrl.$inject = ['$scope', 'post']; 

in controller call post .

post.index({},            function success(data) {                $scope.posts = data;            },          function err(error) {            if(error.status == 401)            {              alert('not auth.');            }            $scope.posts = {};          }   ); 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -