error:
Yes i know there have been posts similar to this one but they do not address my issue. I want to take full control of the app's routing.My code is as follows:
a few things to note would be that i have attached a custom property to my states called authenticate which has a true
or false
value. I have also created a simple function, get user
. All it does is retrieve the user from the api.
$rootScope.$on('$stateChangeStart', function(event, toState) {
event.preventDefault();
let token = $cookies.get('token');
if (toState.authenticate) {
if (token) {
getUser()
.then(user => {
$rootScope.user = user;
$state.go(toState.name);
})
.catch(err => console.log(err));
} else {
$state.go('login');
}
} else {
$state.go(toState.name);
}
});
I first check if the state requires authentication. If it does not we simply continue to the state. If it does require authentication we check if there is a token. if there is we fetch the user using the function I mentioned earlier. If there isn't a token we send the user to the login state.