5

Using UI-router, when a user goes to a page that require's a login, after they login, I would like to redirect them back to the original url they came from.

So for example,

/account/profile --> LOGIN PAGE (/login) --> /account/profile /someother/requiredLogin/path --> LOGIN PAGE (/login) --> /someother/requiredLogin/path 

My routes:

 $stateProvider .state('accountProfile', { url: '/account/profile', data: { requiresLogin: true }, views: { '': { templateProvider: function($templateCache) { return $templateCache.get('templates/profile.html'); } } }, }) .state('anotherPage', { url: '/someother/path', data: { requiresLogin: true }, views: { '': { templateProvider: function($templateCache) { return $templateCache.get('templates/other.html'); } } }, }) 

Inside my application's run block I have:

.run(['$rootScope', '$state', 'LoginService', function($rootScope, $state, LoginService) { // Change title based on the `data` object in routes $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { var requiresLogin = toState.data.requiresLogin; if (requiresLogin && !LoginService.check()) { event.preventDefault(); $state.go('login'); } }); } ]) 

As you can see, I do a basic job at adding a requiresLogin to each route, that just redirects always to login route. How can I keep track of the original URL and redirect them back to it AFTER they login?

1
  • you can i.e. store current state to $rootScope Commented May 20, 2015 at 22:22

1 Answer 1

7

Update your login state configuration to include default parameters for the name of the state to redirect to on login (toState) as well as any parameters passed with the original state change (toParams). If you don't define defaults, $state.params will always be empty when you check for them in your login controller - even if you provide values from your $stateChangeStart handler!

 .state('login', { data: {'requiresLogin': false}, params: { 'toState': 'profile', // default state to proceed to after login 'toParams': {} }, url: 'login', }) 

Modify your run block to capture and pass on the requested (unauthorized) state:

 $state.go('login', {'toState': toState.name, 'toParams': toParams}); 

In your login controller success handler, the following will either send you to the state specified in $stateChangeStart or the default declared in your state configuration:

 $state.go($state.params.toState, $state.params.toParams); 
Sign up to request clarification or add additional context in comments.

1 Comment

'profile', // default state to proceed to after login how can I make it dynamic?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.