Angular:使用$ resource拦截特定请求

时间:2015-05-27 14:12:02

标签: angularjs interceptor angular-resource

我是Angular的新手,正在研究拦截器。我创建了一个角度工厂来从API中获取一些数据:

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

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

我还创建了类似的拦截器:

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

    var connectionInterceptor =  {

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

拦截器效果很好。但它拦截了我所做的每一个http请求,并且我想让它适用于特定的$资源。我在angular $ resource doc中读到,有一种方法可以通过向$ resource添加一个拦截器动作/参数来实现它。所以我试过了:

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

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

哪个不起作用。抛出的错误是:Error in resource configuration for action query. Expected response to contain an object but got an array

我错过了什么?

1 个答案:

答案 0 :(得分:1)

正如你所说,拦截器是全球性的。我必须在我的响应中添加一个测试来检查$ resource URL并添加一些特定的处理。

 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;
});
相关问题