2
votes

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 ?

1
interceptor will always work for each $resource call. - Pankaj Parkar
This guy had the same problem, and resolved it. And I unfortunately don't understand how : stackoverflow.com/questions/23021416/… - Arhyaa
does isArray: false false is missing? - Pankaj Parkar
Why should I use isArray ? - Arhyaa
Could the root cause be that you did not inject connectionInterceptor to the Connection factory? - OrenD

1 Answers

1
votes

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;
});