$ http inteceptor为每个请求多次记录

时间:2016-01-25 19:11:23

标签: angularjs http angular-http-interceptors

我正在创建一个有角度的应用程序,我已添加了一个自定义的$ http拦截器,用于身份验证和记录。

最近,我注意到我的拦截器工厂记录了每次请求4次,并且还记录了每次响应4次。

我添加了一个代码片段来复制此内容,但代码段只会针对每个请求记录一次。



angular.module('app', [])
  .config(appConfig)
  .controller('appCtrl', appCtrl)
  .factory('AuthInterceptor', AuthInterceptor);


appConfig.$inject = ['$httpProvider'];

function appConfig($httpProvider) {
  $httpProvider.interceptors.push('AuthInterceptor');
}

appCtrl.$inject = ['$http'];

function appCtrl($http) {
  var vm = this;
  vm.fakeHttpCall = fakeHttpCall
  vm.result = "text";

  function fakeHttpCall() {
    $http
      .get('/api')
      .then(function(res) {
        vm.result = "success";
      }, function(err) {
        vm.result = "error";
      })
  }

}

AuthInterceptor.$inject = ['$log', '$q'];

function AuthInterceptor($log, $q) {
  return {
    request: request,
    requestError: requestError,
    response: response,
    responseError: responseError
  };

  function request(config) {
    $log.debug(config); // Contains the data about the request before it is sent.

    // Return the config or wrap it in a promise if blank.
    return config || $q.when(config);
  }

  function requestError(rejection) {
    $log.debug(rejection); // Contains the data about the error on the request.

    // Return the promise rejection.
    return $q.reject(rejection);
  }

  function response(res) {
    $log.debug(res);
    return res;
  }

  function responseError(res) {
    $log.debug(res.status);
    return $q.reject(res);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

<body ng-app='app'>
  <div ng-controller="appCtrl as vm">
    <button ng-click="vm.fakeHttpCall()">
      fake $http call
    </button>
    <span>
      {{ vm.result }}
    </span>
  </div>
</body>
&#13;
&#13;
&#13;

0 个答案:

没有答案