Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

Hello I try to make a async call in the response method of a http interceptor in AngularJS. The async call gets fired but then gets stuck in an infinite loop and the async call gets called over and over... Not sure why, I guess the error has to do with the structure of my async call

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

app.service('Ace',['$http','$q','$injector', '$window', function($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');
 });
share|improve this question

1 Answer 1

You'll want to add a check in your Ace service so that getCurrentUser is only making one async call, regardless of how many times it is called.

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;
};
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.