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

前端 未结 7 593
耶瑟儿~
耶瑟儿~ 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:52

    By default angular sends and receives application/json headers. You can get this on the HTTP response header like :

    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) {
            // use this line to if you are receiving json, else use xml or any other type
            var isJson = response.config.headers.Accept.indexOf('json')>-1;
            $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) {
            // use this line to if you are receiving json, else use xml or any other type
            var isJson = response.config.headers.Accept.indexOf('json')>-1;
            // do something on error
            $rootScope.showSpinner = true;
            console.log('failure');
            console.log('status', response.status)
            //return response;
            return $q.reject(response);
          }
        };
      });
    

提交回复
热议问题