我知道如何拦截所有的请求,但我只想拦截从我的资源的请求。
有谁知道如何做到这一点?
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 }]);