AngularJS, $ digest error trying to redirect application to pages requiring login

I am trying to redirect an AngularJS application if the requested state requires login. This is the method that I posted in the "run" method in my angular application:

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { if(toState.data.requiresLogin && !User.isLoggedIn) { event.preventDefault(); $state.go('login'); } }); 

It seems obvious, but I get this digest error. This seems to be called by the event.preventDefault () statement. I can’t remove this, of course ...

 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [["fn: $locationWatch; newVal: 7; oldVal: 6"],["fn: $locationWatch; newVal: 8; oldVal: 7"],["fn: $locationWatch; newVal: 9; oldVal: 8"],["fn: $locationWatch; newVal: 10; oldVal: 9"],["fn: $locationWatch; newVal: 11; oldVal: 10"]] ... 

Any tips on how to reorganize this to clear this error, or what does the error mean?

0
angularjs angular-ui-router
Jul 12 '14 at 3:39
source share
1 answer

There is a working working example on how to redirect login. Firstly, 4 states are defined - 2 of them require authentication, the third one is public (for someone), and there is also an input state:

 $stateProvider // available for anybody .state('public',{ url : '/public', template : '<div>public</div>', }) // just for authenticated .state('some',{ url : '/some', template : '<div>some</div>', data : {requiresLogin : true }, }) // just for authenticated .state('other',{ url : '/other', template : '<div>other</div>', data : {requiresLogin : true }, }) // the log-on screen .state('login',{ url : '/login', templateUrl : 'tpl.login.html', controller : 'UserCtrl', }) 

and it will be $stateChangeStart def, which is always redirected to login - if required ... only login itslef and public are always available / to anyone

 .run(['$rootScope', '$state', 'User', function($rootScope, $state, User) { $rootScope.$on('$stateChangeStart' , function(event, toState, toParams, fromState, fromParams) { var isAuthenticationRequired = toState.data && toState.data.requiresLogin && !User.isLoggedIn ; if(isAuthenticationRequired) { event.preventDefault(); $state.go('login'); } }); }]) 

Make sure everything is in action here.

+1
Jul 13 '14 at 17:08
source share



All Articles