如何使用angularJS拦截器只拦截特定的http请求?
发布时间:2020-12-17 08:29:46 所属栏目:安全 来源:网络整理
导读:我知道如何拦截所有的请求,但我只想拦截从我的资源的请求。 有谁知道如何做到这一点? services.config(['$httpProvider',function($httpProvider) { $httpProvider.interceptors.push('myHttpInterceptor');}]);services.factory("userPurchased",function
我知道如何拦截所有的请求,但我只想拦截从我的资源的请求。
有谁知道如何做到这一点? services.config(['$httpProvider',function($httpProvider) { $httpProvider.interceptors.push('myHttpInterceptor'); }]); services.factory("userPurchased",function ($resource) { return $resource("/api/user/purchases/:action/:item",{},{ 'list': {method: 'GET',params: {action: 'list'},isArray: false},'save': {method: 'PUT',params: {item: '@item'}},'remove': {method: 'DELETE',} ); }); services.factory('myHttpInterceptor',function($q,$rootScope) { // $rootScope.showSpinner = false; return { response: function(response) { $rootScope.showSpinner = false; // do something on success console.log('success'); console.log('status',response.status); //return response; return response || $q.when(response); },responseError: function(response) { // do something on error $rootScope.showSpinner = true; console.log('failure'); console.log('status',response.status) //return response; return $q.reject(response); } }; });
如果只想截获来自特定资源的请求,可以使用$ request操作的可选拦截器属性。 Angular的文档
see here(Usage> actions)
JavaScript angular.module('app',['ngResource']). factory('resourceInterceptor',function() { return { response: function(response) { console.log('response intercepted: ',response); } } }). factory('resourceService',['$resource','resourceInterceptor',function($resource,resourceInterceptor) { return $resource(":name",isArray: false,interceptor: resourceInterceptor} } ); }]). run(['resourceService','$http',function(resourceService,$http) { resourceService.list({name: 'list.json'}); // <= intercepted $http.get('list.json'); // <= not intercepted }]); Plunker:http://plnkr.co/edit/xjJH1rdJyB6vvpDACJOT?p=preview (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- mongodb – Dockerfile中的Mongorestore
- 使用Axis2创建WebService实例
- bash gunzip |解压在分隔文件夹中的多个文件
- angularjs – angular ui-bootstrap datepicker mindate在输
- 在vim编辑器python实现tab补全功能
- Webservice_13_Payload的方式传递SOAP的消息和处理 和 用SO
- twitter-bootstrap – 使用Twitter Bootstrap 3的Laravel 4
- twitter-bootstrap – Twitter Bootstrap,如何使崩溃插件关
- Unix命令查找字符串集合交集或异常值?
- Bootstrap字体图标无法正常显示的解决方法