Reputation: 353
I am doing a simple signin/signup using angularjs using ui.router.
signin route is: common/signin
signup route is: common/signup
code for 'common' state:
$stateProvider.state('common',{
url:'/common',
templateUrl:'templates/common.html',
abstract:true,
resolve:{
//if acces token is found in local storage then change route to portal/dashboard
//else continue to common/signin or common/signup
}
});
Is there a way to change routes inside a resolve. I know this can be done in controller of sign in and sign up. ie: I would check in controller for sign :
app.controller('signinController',['tokenService','$scope','$state',function(tokenService,$scope,$state){
if(tokenService.getToken()!=null){
$state.go('portal.dashboard');
}
}]);
and the same task is to be done in signup controller.
app.controller('signupController',['tokenService','$scope','$state',function(tokenService,$scope,$state){
if(tokenService.getToken()!=null){
$state.go('portal.dashboard');
}
}]);
But it will be a duplicate code and I always question myself before doing duplication. And also doing this flashes the signin or signup template and then shows dashboard.
So I was thinking about a way to check the same while routing in common state. Is there a way to do this through a service such that I can do:
if(token found in local storage){
$q.reject();
$state.go('portal.dashboard')
}
else{
$q.resolve();
//continue to do /signup or /signin
}
Upvotes: 1
Views: 990
Reputation: 5435
you can inject $timeout
$stateProvider.state('common',{
url:'/common',
templateUrl:'templates/common.html',
abstract:true,
resolve:{
auth:function($timeout,$state,$q){
if(token found in local storage){
$timeout(function(){
$state.go('dashboard')
})
return $q.reject();
}
else{
return $q.resolve(token);
}
}
}
});
something like this will work
Upvotes: 1
Reputation: 2114
You are using states, so I would use
$state.go(state);
https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options
If you want to have multiple child states of your common state, you can look into using nested states:
https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views
Upvotes: 0