0

In Angular, I would like to have a function that intercepts the $resource response before it gets to the controller to see if it has an error flag set and then act on that error flag. Is there a resource function I can hook into to check the response data before it sends it on it's way to the controller?

Sample resource :

mymod.factory('setSomething', function($resource){
    var resource = $resource('/proxy/request.php?action=setSomething', {}, {
        post:{
            method  : "POST",
            isArray : false,
            headers : { 
                'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' 
            } 
        },

    });
    return resource;
});
Tim Joyce
  • 4,487
  • 5
  • 34
  • 50
  • Check this other answer, should give it exactly what you need. http://stackoverflow.com/questions/18582900/usage-of-interceptor-within-resource – pedromarce Feb 21 '14 at 13:28
  • You can probably use an $http interceptor. There's a good post [here](http://djds4rce.wordpress.com/2013/08/13/understanding-angular-http-interceptors/) about interceptors. – maxdec Feb 21 '14 at 13:36

1 Answers1

0

You can define error handling for resources globally:

$httpProvider.interceptors.push(function($q, $rootScope) {
  return {
     'request': function(config) {
        // intercepts the request
     },
     'response': function(response) {
       // intercepts the response. you can examine things like status codes
     },
     'responseError': function(response) {
       // intercepts the response when the response was an error
     }
  }
});

The response parameter gives you a lot of information to work with so you can handle errors appropriately.

Steve Davis
  • 716
  • 5
  • 13