How to use angularJS interceptor to only intercept specific http requests?

前端 未结 7 589
耶瑟儿~
耶瑟儿~ 2020-12-23 21:17

I know how to intercept ALL requests, but I only want to intercept requests from my resources.

Does anyone know how to do this?

services.config([\'$h         


        
7条回答
  •  悲&欢浪女
    2020-12-23 21:45

    If you want to intercept only requests from specific resources, you can use optional interceptor property of $request action. Angular's documentation 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", 
            {}, 
            {
                '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

提交回复
热议问题