【发布时间】:2014-06-07 02:35:27
【问题描述】:
如何向$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 调用分配一个拦截器?
【问题讨论】:
-
你好@Unidan。一年后……你的问题有答案了吗?
标签: angularjs http rest resources interceptor