I use the following to redirect routes to login if a user is not logged in:
angular.module('app').run(['$rootScope', '$location', '$state', 'AuthService',
function($rootScope, $location, $state, AuthService) {
/* redirect to login if not logged in */
$rootScope.$on( '$stateChangeStart',
function(e, toState, toParams, fromState, fromParams) {
if(toState.name === "login"){
return; // already going to login
}
if(!AuthService.user) {
e.preventDefault();
$state.go('login');
}
});
}]);
How can I pass the url from the "prevented" state to the login state so that I can continue navigating to that state once logged in?
Example: User clicks link for myapp.com/#/path/to/data --> redirects to myapp.com/#/login --> user logs in --> user routed to myapp.com/#/path/to/data
I basically need /path/to/data to be sent to my login controller so that I can handle that. I cannot seem to find '/path/to/data' in any of the state or param variables in the $stateChangeStart listener.
The $state
service has an href
method which can create a URL given the state and its parameters. Since those are provided to the state change listener, you can create a URL and then pass it as a param to the login state.
$rootScope.$on('$stateChangeStart',
function(e, toState, toParams, fromState, fromParams) {
if (toState.name === "login") {
return; // already going to login
}
if (!AuthService.user) {
e.preventDefault();
var redirectUrl = $state.href(toState.name, toParams);
$state.go('login', {
redirect: redirectUrl
});
}
});
You'll need to add a redirect
parameter to your login state so you can use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With