Uni*_*dan 15 rest resources http interceptor angularjs
如何在$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
}
);
}]);
Run Code Online (Sandbox Code Playgroud)
我的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;
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
首先,request
拦截功能永远不会执行,为什么不呢?
其次,必须将拦截器硬编码到现有$resource
方法是非常繁琐的,有没有办法更容易地将拦截器分配给特定的$resource
调用,或者甚至可能为所有$resource
调用分配拦截器?
JDL*_*JDL 15
要在资源中使用拦截器,您应该:
1 - 使用request,response,responseError创建一个httpInterceptor:
app.factory('myInterceptor', function () {
//Code
//return { request:...,
});
Run Code Online (Sandbox Code Playgroud)
2 - 在你的应用中配置这个拦截器:
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('myInterceptor');
}]);
Run Code Online (Sandbox Code Playgroud)
现在你已经配置你的httpProvider有一个拦截器无论你注入$ http你将使用这个提供程序,所以...你将执行你的请求,响应和responseError函数.
3 - 在资源中使用它.由于$ resource使用$ http并且你配置了一个httpProvider globaly,你将在使用你的资源时调用你的拦截器的func.
第二个问题:你不能将拦截器设置为具体的$ 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...
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17876 次 |
最近记录: |