My current setup involves Angular 1.5.8
and angular-ui-router 0.3.2
. Every time a route changes, I need to authenticate the user.
To avoid adding the resolve property for each route individually, I decided to handle this in App.run
//check permissions
$rootScope.$on('$stateChangeStart', function (evt, toState) {
if ($localStorage.token || toState.authenticated) {
$http.defaults.headers.common = {
'Authorization': 'Token ' + $localStorage.token,
'Accept': 'application/json'
};
permissionAPI.me()
.then(function(data){
$rootScope.user = data;
})
.catch(function(){
if(toState.authenticated) {
$rootScope.logout();
}
})
}
else {
if(toState.authenticated) {
$rootScope.logout();
}
}
});
`
While this approach generally works fine, there are instances where the application routes before the promise permissionAPI.me()
is resolved, leading to errors later on.
How can I ensure that the route only takes effect after the promise has been fulfilled?
Alternatively, is there a way to set up a single main resolve
for all routes by passing the promise from $stateChangeStart
?
Thank you!