I am trying to redirect inside a ui-router resolve and wanted to know if there is a way to reroute in a router resolver. Currently this does not work as one would think.
resolver(auth, $state){
if(!auth.isLoggedIn()){
$state.go('noLoggedInPath');
}
}
How does one redirect in a resolver correctly ?
My temp hack is this but I am not comfortable with it.
resolver(auth, $state, $timeout){
if(!auth.isLoggedIn()){
$timeout(function () {
$state.go('noLoggedInPath');
}, 0);
}
}
Yauheni's answer does work, but to get around the weird timeout thing, you can reject the promise, and catch that in the $stateChangeError event, and do your redirect there. Like so...
And then ui-router always broadcasts "stateChangeError", so you can do something like this..
You can use resolver promises from with the redirectTo configuration
I think a much cleaner answer is to return an already rejected promise like so:
You can return a promise from your
resolver
function that will indicate whether to continue navigating to the state or not. If you decide to navigate somewhere else - reject the promise and specify the proper state:Plunkr here.
UPD: updated code and added plunkr. Looks like it only works if you put it inside a timeout function.
Using resolves for this didn't quite work out for me. I adapted the logic from this post to execute a redirect function on the data property of the state object. You can then tap into the $stateChangeStart event on $rootScope from the run block of the module and use the injector service's invoke method to the change the state based on the conditions you specify. Works nicely across modules as well.
This is what I actually do, and I can't find a better solution