Using UI-Router, I need to check the existing token every time a state change is initiated. The issue only occurs on the initial page load, and disappears upon refreshing the page.
Below is the code snippet that I suspect might be causing the error:
.run(['$rootScope', '$location', '$state', '$http', '$window', 'APIROOT', function ($rootScope, $location, $state, $http, $window, APIROOT) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
var isLogin = toState.name === "login";
if (isLogin) {
return;
}
var userInfo = $window.sessionStorage.token;
if (!userInfo) {
event.preventDefault();
$state.go('login');
} else {
$http.get(APIROOT + 'check_token').then(function(resp){
return true;
}).then(function(err){
})
}
});
}]);
My Controller:
angular.module('app')
.controller('AppCtrl', ['$http', '$scope', '$window', 'APIROOT', AppCtrl]);
function AppCtrl($http, $scope, $window, APIROOT) {
var date = new Date();
var year = date.getFullYear();
$scope.main = {
name: $window.sessionStorage.getItem('name'),
brand: 'Brand',
year: year
};
}
The first solution I found was to change "$stateChangeStart" to "$stateChangeSuccess", but I prefer to perform the check before the state changes successfully. What should I fix?