2

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 ?

Arhyaa
  • 369
  • 1
  • 3
  • 21
  • interceptor will always work for each `$resource` call. – Pankaj Parkar May 27 '15 at 14:21
  • This guy had the same problem, and resolved it. And I unfortunately don't understand how : http://stackoverflow.com/questions/23021416/how-to-use-angularjs-interceptor-to-only-intercept-specific-http-requests – Arhyaa May 27 '15 at 14:24
  • does `isArray: false` false is missing? – Pankaj Parkar May 27 '15 at 14:25
  • Why should I use `isArray` ? – Arhyaa May 27 '15 at 14:27
  • Could the root cause be that you did not inject `connectionInterceptor` to the `Connection` factory? – OrenD May 27 '15 at 14:29
  • You mean in the `return $resource('...')` ? I injected it in the module with `$httpProvider.interceptors.push('connectionInterceptor')`and it worked perfectly on every http request I made. It seems to work if I replace `query` by a string but I still don't understand why. – Arhyaa May 27 '15 at 14:34

1 Answers1

1

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;
});
Arhyaa
  • 369
  • 1
  • 3
  • 21