2016-04-14 116 views
0

每当我在任何请求前发出$ http请求时,我都会遇到流行的循环依赖问题。我已经看到了之前对这些问题:

我真的,如果这些问题上面都试图让我想同样的事情不知道实现。我想创建一个$ http请求来检查我的JWT令牌的完整性,我需要在我的服务器端执行此操作。如果令牌已过期,我需要让用户获得另一个令牌。

这里是我的代码

var app = angular.module('app', ['ngRoute', 'ngStorage']); 

app.factory('requestInterceptor', ['$q', '$localStorage', '$location', function($q, $localStorage, $location) 
{ 
    var requestInterceptor = {}; 

    requestInterceptor.request = function(config) 
    { 
//  $http 
//  ({ 
//   url : 'api/token', 
//   method: 'GET', 
//   headers : { Authorization : $localStorage.token} 
//  }).then(function(response){ 
//   $localStorage.token = response.data.token; 
//  },function(response){ 
//   $localStorage.token = null; 
//   $location.path('/'); 
//  });   

     config.headers = config.headers || {}; 
     if ($localStorage.token) 
     { 
      config.headers.Authorization = 'Bearer ' + $localStorage.token; 
     } 
     return config;   
    }; 

    requestInterceptor.responseError = function (response) 
    { 
     if (response.status === 401 || response.status === 403) 
     { 
      $location.path('/signin'); 
     } 
     return $q.reject(response); 
    }; 

    return requestInterceptor; 
}]); 

注意

不能使用Angular-JWT

回答

0

尝试抽象令牌验证到不同的服务。我没有测试它,但它应该工作。

app.factory('auth', ['$http', '$localStorage', '$location', function($http, $localStorage, $location){ 
    return { 
    validateToken: function() { 
     return $http({ 
     url : 'api/token', 
     method: 'GET', 
     headers : { Authorization : $localStorage.token} 
     }).then(function(response){ 
     $localStorage.token = response.data.token; 
     return response.data.token; 
     },function(response){ 
     $localStorage.token = null; 
     $location.path('/'); 
     });  
    } 
    } 
}]); 

app.factory('requestInterceptor', ['auth', function(auth){ 
    var requestInterceptor = {}; 

    requestInterceptor.request = function(config){ 
    if (!config.url.startsWith('api/token')) { 
     auth.validateToken().then(function(token){ 
     config.headers = config.headers || {}; 
     config.headers.Authorization = 'Bearer ' + token; 
     return config; 
     }); 
    } else { 
     return config; 
    } 
    }; 

    return requestInterceptor; 
}]); 
+0

我得到$ http未定义。如果我包含$ http服务,我会得到循环依赖问题 – ggderas