I am having an issue with login timing in an angular app. My intention is that when a user logs in, that the API key is then set in localStorage and is available to call on for accessing the API. After login, I want the app to redirect the user to the home state. But what is happening is that the user is redirected, gets a 401 - and based off what I have setup - is then redirected back to login. If I do a hard refresh on the browser after logging in it works. Here is what I have going.
.factory('localStor', function($q, $log, $window, $rootScope) {
var apiKey = false;
return {
getAPI: function() {
return $q(function(resolve, reject) {
var data = $window.localStorage.getItem('apiKey');
if (data == null) {
return $rootScope.$broadcast('notAuthorized');
} else {
var key = data;
return resolve(key);
}
});
},
setAPI: function(key) {
return $q(function(resolve, reject) {
apiKey = false;
if (key === undefined) {
return reject();
}
return $window.localStorage.setItem('apiKey', key);
});
}
}
})
function getLogin(email, password) {
return $q(function(resolve, reject) {
$http({
method: 'POST',
data: {
'email': email,
'password': password
},
url: config.api.baseUrl + '/user/login'
}).then(function(result) {
if (result) {
var token = result.data.data.token;
resolve(token);
} else {
$log.debug('Incorrect email or password');
reject(1);
}
}, function(reason) {
reject(2);
});
})
}
$scope.submitLogin = function(email, password, form) {
$scope.errorNote = false;
if (form.$valid) {
$scope.loading = true;
login.getAPI(email, password).then(function(data) {
var key = data;
localStor.setAPI(key).then(function() {
$timeout(function() {
$state.go('app.loading', {}, { reload: true });
}, 30);
});
$scope.loading = false;
}, function(reason) {
$scope.errorNote = reason;
$scope.loading = false;
});
}
};
My calls to the API are then set up like this
var apiKey = false;
localStor.getAPI().then(function(data) {
apiKey = data;
$log.debug(apiKey);
}, function() {
$rootScope.$broadcast('notAuthorized');
});
function withApiKey(callback, errorcallback) {
localStor.getAPI().then(function(data) {
if (typeof callback === 'function') {
callback(data);
}
}, function(err) {
if (typeof errorcallback === 'function') {
errorcallback(err);
}
});
}
function notificationCount() {
return $q(function(resolve, reject) {
withApiKey(function(key) {
$http({
method: 'GET',
headers: { 'Authorization': 'Bearer ' + key },
url: config.api.baseUrl + '/user/notifications/count'
}).then(function(result) {
if (result) {
resolve(result);
} else {
reject('Uh Oh');
}
}, function() {
reject('Uh Oh');
});
});
})
}