问题
Hi I am just starting to learn angular && angular-ui-router and am trying to figure out how to determine when the app is opened for the first time to send the user to the login page or home page.
This is what i have so far:
codeArtApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('login',{
url : '/login',
templateUrl:'App/scripts/login/loginView.html',
controller: 'loginCtrl'
})
.state('profile', {
url : '/profile',
templateUrl:'App/scripts/login/loginView.html',
controller: 'profileCtrl'
})
.state('404', {
url: '/404',
templateUrl:'App/scripts/views/404.html'
});
$urlRouterProvider.otherwise("404");
});
codeArtApp.run(['$state', '$rootScope', function($state, $rootScope, $log){
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState){
if(fromState.url === '^' && toState.url !== 'login'){
$state.go('login');
}
});
}]);
What I assumed here is that if fromState.url
is set to ^
then the application is starting for the first time.
For some reason this code enters an infinite loop and I gt this stacktrace:

Now from what I can tell this happened because event if $state.go('login')
gets execute toState.url
is always 404.
I had hoped if $state.go('login')
gets executed toState.url
would have been set to login and that call would not be executed anymore.
I may not be setting this logic in the right place...
Can anyone tell me how conditionaly page displayed is achieved in Angular?
回答1:
There is a link to working plunker, the main changes are shown in the code:
codeArtApp.run(['$state', '$rootScope',
function($state, $rootScope, $log) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState) {
// instead of
// toState.url !== 'login'
// we compare
// toState.name !== 'login'
var shouldLogin = fromState.url === '^'
&& toState.name !== 'login';
if(shouldLogin)
{
// this way we stop current execution
event.preventDefault();
// and navigate to login
$state.go('login');
}
});
}
]);
The toState.url
would contain the url, i.e. '/login'
instead of 'login'
. Also check the : State Change Events to see more about the event.preventDefault();
. The plunker showing the above...
回答2:
In your $urlRouterProvider.otherwise
call you can pass a function instead of a string. Something like this:
$urlRouterProvider.otherwise(function($injector){
var $state = $injector.get('$state');
var Storage = $injector.get('Storage');
if (Storage.has('authToken')) {
$state.go('home');
}
else {
$state.go('login');
}
});
Hope this helps!
来源:https://stackoverflow.com/questions/24349977/conditional-page-display-when-application-opens-for-the-first-time