如何向$resource调用添加拦截器?
假设我有一个名为Users的资源工厂,如下所示;
app.factory('Users', ['$resource', 'resourceInterceptor',
function ($resource, resourceInterceptor) {
return $resource(
'users/:user_id',
{
user_id: '@id'
},
{
query: {
method: 'GET', // Not changing the default method, just adding an interceptor
interceptor: resourceInterceptor // Is there any better way to do this.. like globally?
},
save: {
method: 'POST', // Same here
interceptor: resourceInterceptor // Again...
},
..., // And so on
}
);
}]);我的resourceInterceptor服务看起来像这样;
app.factory('resourceInterceptor', ['$rootScope',
function ($rootScope) {
return {
request: function () {
// This function isn't executed at all?
$rootScope.loading = true;
},
response: function () {
$rootScope.loading = false;
},
responseError: function () {
$rootScope.loading = false;
}
};
}]);首先,request截取函数从不执行,为什么不执行呢?
其次,必须将拦截器硬编码到现有的$resource方法是非常乏味的,有没有一种方法可以更容易地将拦截器分配给特定的$resource调用,或者甚至可以将拦截器分配给所有$resource调用?
发布于 2014-06-19 16:02:36
要在资源中使用拦截器,您应该:
1-使用您的请求、响应和responseError创建httpInterceptor:
app.factory('myInterceptor', function () {
//Code
//return { request:...,
});2-在应用程序中配置此拦截器:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);现在,因为您已经将您的httpProvider配置为在您注入$http的任何地方都有一个拦截器,所以您将使用此提供程序...你将执行你的请求,响应和responseError函数。
3-在资源中使用它。因为$resource使用$http,并且你已经在全球范围内配置了一个httpProvider,所以当你使用你的资源时,你将调用拦截器的函数。
第二个问题:您不能将拦截器设置为具体的$http对象,它们(拦截器)是全局设置的。
(即使您在模块定义之前设置了拦截器,然后将其删除,您也无法知道执行顺序)
您可以做什么如果您不想覆盖每个$resource操作中的拦截器属性(正如您在问题中所写的),您可以改进您的拦截器。
app.factory('userLoadingInterceptor', function () {
//Code
return {
request: function(){
//Check if your are working with a url related with users
// and if so do things...
}
});发布于 2014-04-23 00:27:47
从文档中:
响应拦截器对象有两个可选方法-
和responseError
我不知道您想要实现什么,但是通用HTTP拦截器可能是一种替代方案。
发布于 2014-04-23 00:55:20
一个通用的HTTP拦截器应该可以做你想做的事情。您可以在此处找到一个示例:Handle HTTP 302 response from proxy in angularjs。
https://stackoverflow.com/questions/23224337
复制相似问题