Basically what I'm trying to do is change the state depending on user authentication status.
When I do $state.go();
without $rootScope, I can redirect to the page without the error but when I do with
$rootScope.$on('$stateChangeStart', function (event) {
$state.go();
event.preventDefault()
})
Below Is the Controller Code:
DiaryDashboard.controller('AppController',
['$scope', '$rootScope', '$localStorage', '$http', '$state'
, function ($scope, $rootScope, $localStorage, $http, $state) {
$rootScope.$on('$stateChangeStart', function (event, toState) {
if ($localStorage.userdetails &&
$localStorage.userdetails.isAuthenticated == true) {
//Check for Authentication state
//If not redirect to the state in the else clause
//Populate the $rootScope with user details
$rootScope.userdetails = $localStorage.userdetails;
//Switch to the parent state
$state.go();
event.preventDefault();
} else {
//If User not authenticated
//GO to the Authentication State
$state.go('auth');
event.preventDefault();
}
})
}]);
Use $state.go("main", {}, {notify:false}); for not notify to "$stateChangeStart"event and not allow the event loop.
You are basically creating a state change interceptor.
The thing is, on every one of your branches in '$stateChangeStart' you have a $state.go . Since this is an interceptor, every time you invoke $state.go , the handler for $stateChangeStart will be invoked, and this is why you get this invocation loop that ends with that error.
You need to write the handler in a way that has at least one branch that does not invoke $state.go
Here is how we implemented it:
The most important thing here is to understand this:
Check this Q & A:
Angularjs ui-router. How to redirect to login page
the adjusted code:
You are creating a redirection loop. You need to check whether the new route is already the route where you want to send your client to.
Your code is going in infinite as you are doing
$state.go
in both cases, You could should not do$state
redirection user is authorized & second condition is proper which is in else blockUpdate
Other thing which I wanted to point out about your code is
$stateChangeStart
should be inside a run block(which initialize exactly after config block) so that It would be common for all state & will initialized this condition at the starting of your appCode
Also do use service to store
UserDetails
using$rootScope
in AngulaJs is considered as bad code practice.