1

我正在制作一个角度应用程序,并且我添加了一个自定义 $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>

4

0 回答 0