Search code examples
angularjsinterceptorangular-resource

Angular : intercept specific request with $resource


I'm new to Angular, and am working on an interceptor. I created an angular factory to get some data from an API like that :

app.factory('Connection',['$resource',function($resource) {

    return $resource('url',{param1: '1',param2: '55'},);
}]);

I also created the interceptor which looks like that :

app.factory('connectionInterceptor', function($q,$location) {

    var connectionInterceptor =  {

        response: // code here
        responseError: // code here
    };
    return connectionInterceptor;
});

The interceptor works well. But it intercepts every http request I do, and I'd like to make it work for a specific $resource. I read in angular $resource doc that there is a way to make it by adding an interceptor action/param to $resource. So I tried :

app.factory('Connection',['$resource',function($resource) {

    return $resource('http://localhost:8080/api/login',{user: '1',password: '55'}, {}, 
        query: {
            method : 'GET',
            interceptor : 'connectionInterceptor'
        }
    });
}]);

which didn't work. The thrown error is : Error in resource configuration for action query. Expected response to contain an object but got an array.

What did I miss ?


Solution

  • As you said, interceptors are globally set. I had to add a test to my response to check the $resource URL and add some specific treatment.

     module.factory('interceptor', function() {
    
         var interceptor =  {
    
            response: function(response) {
    
               if (response.config.url.startsWith('my url')) {
                   // some treatment
               }
               else
                   // other treatment
               return response;
            }
            return connectionInterceptor;
    });