如何使用angularJS拦截器只拦截特定的http请求?

前端之家收集整理的这篇文章主要介绍了如何使用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',}
    );
});

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

猜你在找的Angularjs相关文章