Angular JS http拦截器异步调用无限循环

时间:2015-08-05 13:22:34

标签: javascript angularjs asynchronous angular-http-interceptors

您好我尝试在AngularJS中的http拦截器的响应方法中进行异步调用。异步调用被触发但随后被卡在无限循环中并且异步调用被反复调用...不确定为什么,我猜错误与我的异步调用的结构有关

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

app.service('Ace',['$ http','$ q','$ injector','$ window',函数($ http,$ q,$ injector,$ window){

this.user = null;

var setToken = function(token){
    $window.localStorage.token = token;
};

var removeToken = function(){
    $window.localStorage.token = '';
}

var setCurrentUser = function(currentUser){
    user = currentUser;
};

var getCurrentUser = function(){
    var self = this;
    var url = "http://localhost:8080/api/currentuser";

    var response = $http.post(url, {}).then(function(response){
        if(response.data.data["obj"]){
            self.user = response.data.data["obj"];
        }

        return response;
    });

    return response;
};

var currentUser = function(){
    return user;
};

return {
    setToken: setToken,
    setCurrentUser: setCurrentUser,
    getCurrentUser: getCurrentUser,
    currentUser: this.user,
    removeToken: removeToken
  }

  }]);


app.factory('authInterceptor',['$rootScope', '$q', '$window', '$injector', 
function ($rootScope, $q, $window, $injector) {
return {
request: function (config) {
  config.headers = config.headers || {};
  if ($window.localStorage.token) {
    config.headers.Authorization = 'Bearer ' + $window.localStorage.token;
  }
  return config;
},
response: function(response) {
    var deferred = $q.defer();

    var Ace = $injector.get('Ace');
    Ace.getCurrentUser().then(function(){
        deferred.resolve(response);
    });

    return deferred.promise;    
    }
   };
   }]);

 app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
 });

1 个答案:

答案 0 :(得分:0)

您需要在Ace服务中添加一项检查,以便getCurrentUser只进行一次异步调用,无论调用多少次。

var callStatus = false;
var getCurrentUser = function() {
    var self = this;
    var url = "http://localhost:8080/api/currentuser";

    if(!callStatus) {
        callStatus = $http.post(url, {}).then(function(response){

        if(response.data.data["obj"]){
            self.user = response.data.data["obj"];
        }});
    }

    return callStatus;
};