Interceptor for all http requests in angularJS 1.0.x

后端 未结 2 1293
孤街浪徒
孤街浪徒 2021-01-01 01:59

I am currently working in a angular app in whcih I wanted to write an interceptor for all http request from my app which in turns calls a service to know whether the single

相关标签:
2条回答
  • 2021-01-01 02:46

    You can use interceptor very easily

    Here is a sample

    var mydevices = angular.module('deviceDetails', ['ui.bootstrap', 'tags-input'])
    
    mydevices.config(function ($httpProvider) {
    $httpProvider.interceptors.push(function($q) {
          return {
           'request': function(config) {
               if (config.method === 'GET' && config.url.contains("/rest/")) {
                   var sep = config.url.indexOf('?') === -1 ? '?' : '&';
                   config.url = config.url + sep + 'cacheSlayer=' + new Date().getTime();
               }
               console.log(config.url);
               return config || $q.when(config);
            }
          };
        });
    });
    

    The example above modifies the URL for all /rest/ URLs

    Hope this helps

    0 讨论(0)
  • 2021-01-01 03:02

    There is a good example in the official documentation working for the current stable 1.2.0.

    [http://docs.angularjs.org/api/ng.$http][1] (top quarter of the page, search for Interceptors)

    angular.module('RequestInterceptor', [])
      .config(function ($httpProvider) {
        $httpProvider.interceptors.push('requestInterceptor');
      })
      .factory('requestInterceptor', function ($q, $rootScope) {
        $rootScope.pendingRequests = 0;
        return {
               'request': function (config) {
                    $rootScope.pendingRequests++;
                    return config || $q.when(config);
                },
    
                'requestError': function(rejection) {
                    $rootScope.pendingRequests--;
                    return $q.reject(rejection);
                },
    
                'response': function(response) {
                    $rootScope.pendingRequests--;
                    return response || $q.when(response);
                },
    
                'responseError': function(rejection) {
                    $rootScope.pendingRequests--;
                    return $q.reject(rejection);
                }
            }
        });
    

    Instead of counting the pendingRequests, you can store the current time, lets say as lastRequestTimestamp. If you combine this with a globally running timer, you can detect how long ago the last request was.

    0 讨论(0)
提交回复
热议问题