Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass url to $stateChangeStart of ui-router

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.

like image 552
Warpasaur Avatar asked Nov 09 '22 05:11

Warpasaur


1 Answers

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.

like image 79
Anid Monsur Avatar answered Nov 15 '22 04:11

Anid Monsur