AngularJS $资源拦截器
如何将拦截器添加到$资源调用?
假设我有一个名为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; } }; }]); 首先,请求拦截功能永远不会执行,为什么不执行? 其次,必须将拦截器硬编码到现有的$资源方法是非常乏味的,有没有办法更容易地将拦截器分配给特定的$资源调用,甚至可以为所有$资源调用分配一个拦截器?
要在资源中使用拦截器,您应该:
1 – 制作一个httpInterceptor与你的请求,响应,responseError: app.factory('myInterceptor',function () { //Code //return { request:...,}); 2 – 在您的应用程序中配置此拦截器: app.config(['$httpProvider',function ($httpProvider) { $httpProvider.interceptors.push('myInterceptor'); }]); 现在,你配置你的httpProvider有一个拦截器,无论你注入$http,你将使用这个提供者,所以你会排除你的请求,响应和响应错误功能. 3 – 在资源中使用它. 第二个问题: (即使您在模块定??义之前设置拦截器,然后将其删除,则无法知道执行顺序) 如果您不想覆盖每个$资源操作中的拦截器属性(如您在问题中写的),您可以执行什么操作,可以改进拦截器. app.factory('userLoadingInterceptor',function () { //Code return { request: function(){ //Check if your are working with a url related with users // and if so do things... } }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- Bootstrap使用响应式设计(Responsive design)时导航条上部有
- codis错误:ResponseError: handle response, backend conn
- scala – 为什么这个未来列表转换的列表编译和工作?
- twitter-bootstrap – 使用Phoenix删除方法的Bootstrap样式
- shell for循环
- angularjs – 如何在节点/ angular / nginx应用程序上强制缓
- angularjs – Angular UI-Grid:过滤后如何获取总项数
- AngularJS访问指令模板中的DOM元素
- macos – 如何调试$PATH?
- unit-testing – 如何使用$location服务单元测试angularjs控