0

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');
 });

1 Answer 1

0

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;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.