如何使用angularJS拦截器仅拦截特定的HTTP请求?

我知道如何拦截所有请求,但是我只想拦截来自我资源的请求。

有谁知道如何做到这一点?

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', params: {item: '@item'}},

}

);

});

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);

}

};

});

回答:

如果只想拦截来自特定资源的请求,则可以使用可选interceptor$requestaction

属性。Angular的文档请参见此处(用法>操作)

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",

{},

{

'list': {method: 'GET', 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

以上是 如何使用angularJS拦截器仅拦截特定的HTTP请求? 的全部内容, 来源链接: utcz.com/qa/403151.html

回到顶部