Reputation: 5230
I have an angular app. I am using ui-router to manage my states. I need to call a common API to check whether the user is allowed to view the web page or not. Is there a common place where I can call the API and only then proceed to the state the user is requesting for?
With my current implementation, the view partially gets displayed and then the reroute happens.
//app.js
$rootScope.$on('$stateChangeSuccess', function(evt, toState) {
if(toState.name === 'login' || toState.name === 'payment')
return;
userService.isBillingCleared().then(function() {
//redirect to toState
}, function() {
$state.go('payment');
});
});
How do I prevent this?
Upvotes: 0
Views: 338
Reputation: 2465
I was facing similar issue while developing a system and the only difference was that I was using default router that is provided by angular but obviously that wont cause any problem.
Keep the data hidden before checking the authentication level of the user and make directive to centralize the whole process. Let's imagine it this way - the view in question that you'll be showing to the user is hidden unless the details are being checked and until then show them any preloader or something or whatever animation you want to.
This is what generally people do in case of a web app or any mobile application, clog the data unless you are sure that yes the data is ready to be viewed.
This practice can be useful even in use case where you are loading the data after the page is being loaded, for e.g. let's say I am showing transactions to user but the transactions are loaded only after the user calls for the view so a call to the backend is made when the view is called that means the user can see for a split second only - an empty table. So...just make use of a preloader and call for the function first and then let the user see the table.
Upvotes: 0
Reputation: 5957
Try this link which talks about authentication for routes in ui-router. Seems like this would be a good solution for you.
Upvotes: 0
Reputation: 778
Try the following
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) {
if(toState.name === 'login' || toState.name === 'payment')
return;
event.preventDefault(); // prevent the state change
userService.isBillingCleared().then(function() {
$state.go(toState.name); // do the state change manually if allowed
}, function() {
$state.go('payment');
});
}));
Upvotes: 1