AngularJS:使用拦截器更新令牌(使用service)

AngularJS: renew token with interceptor (using service)

本文关键字:令牌 使用 service 更新 AngularJS      更新时间:2023-09-26

我有这样的拦截器代码:

var responseError = function(rejection) {
if (rejection.status === 401 || rejection.status === 403) {
authService.renewToken($localStorage.refreshToken).then(function () {
          });
        }
}

,当然,在这段代码的开头,我包括了authService "injector",比如

    ['$q', '$injector', '$location', '$localStorage', '$rootScope', '$window', 'authService', 
 function($q, $injector, $location, $localStorage, $rootScope, $window, authService) {...

和在服务中我有这样的代码:

var renewToken = function(token) {
  var data = /**/
  var deferred = $q.defer();
  $http.post('token', data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    .success(function(response) {
      deferred.resolve(response);
    }).error(function (err) {
      deferred.reject(err);
    });
  return deferred.promise;
};

但是在这段代码中,我得到:

Uncaught Error: [$injector:cdep] Circular dependency found: $http <- authService <- authInterceptorService <- $http <- $templateRequest <- $route

我怎么能更新我的令牌,当我在拦截器中得到异常?

在拦截器中你不必包括authService,只注入$injector

你的responseError函数应该像这样:

var responseError = function(rejection) {
    if (rejection.status === 401 || rejection.status === 403) {
        var authService = $injector.get('authService');
        authService.renewToken($localStorage.refreshToken).then(function () {
        });
    }
}