Skip to content

Instantly share code, notes, and snippets.

@leon
Created September 13, 2013 13:47
Show Gist options
  • Save leon/6550951 to your computer and use it in GitHub Desktop.
Save leon/6550951 to your computer and use it in GitHub Desktop.
ui-router resolve
$stateProvider.state('main', {
abstract: true,
url: '/:account',
resolve: {
auth: function ($q, $state, $stateParams, $location, AccountRepo, Security) {
return AccountRepo.auth().then(function (user) {
// If not logged in redirect to login with path preserved
if (user === false) {
$state.go('account.login', {redirect: $location.url()});
return $q.reject('not logged in');
}
// If account is set in path, set it in the SecurityService otherwise redirect to change account
if ($stateParams.account) {
Security.setAccount($stateParams.account);
} else {
$state.go('account.changeaccount');
return $q.reject('no account selected');
}
return user;
});
}
},
templateUrl: 'app/Main.tpl.html',
controller: 'MainCtrl'
});
@vipulsodha-zz
Copy link

how can we use resolve to protect a state ?
Suppose i create a auth service ! how to redirect if the auth fails in resolve ? i am trying to use $state.go inside resolve but it is not working ?

@josephniet
Copy link

Not quite sure why but $state.go doesn't work inside a resolve (probably because it's already in the middle of a state change). You can use $location.path() instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment