一旦用户登录到我们的应用程序用户凭据存储到本地存储中。如果登录的用户路由状态作为他已登录,其显示以下在控制台中的错误︰
Uncaught Error: [$rootScope:infdig] http://errors.angularjs.org/1.3.10/$rootScope/infdig?p0=10&p1=%5B%5D
代码检查本地存储区,并将用户重定向
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
// Grab the user from local storage and parse it to an object
var user = JSON.parse(localStorage.getItem('user'));
// If there is any user data in local storage then the user is quite
// likely authenticated.
if(!user) {
if(toState.name !== 'login.signin'){
//go to application "login" state
$state.go('login.signin');
event.preventDefault();
}
}
else{
// The user's authenticated state gets flipped to
// true so we can now show parts of the UI that rely
// on the user being logged in
$rootScope.authenticated = true;
// Putting the user's data on $rootScope allows
// us to access it anywhere across the app.
// Here we are grabbing what is in local storage
$rootScope.currentUser = user;
if(toState.name === "login.signin") {
// go to the application "dashboard" state
$state.go('app.dashboard');
// Preventing the default behavior allows us to use $state.go
// to change states
event.preventDefault();
}
}
});
我的解决方案是
Changing $stateChangeStart with $stateChangeSuccess
当你运行你的消化圈不能改变任何范围变量我认为 u 使用$timeout。注入的 $timeout u 定义它的地方
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$timeout(function(){
var user = JSON.parse(localStorage.getItem('user'));
// If there is any user data in local storage then the user is quite
// likely authenticated.
if(!user) {
if(toState.name !== 'login.signin'){
//go to application "login" state
$state.go('login.signin');
event.preventDefault();
}
}
else{
// The user's authenticated state gets flipped to
// true so we can now show parts of the UI that rely
// on the user being logged in
$rootScope.authenticated = true;
// Putting the user's data on $rootScope allows
// us to access it anywhere across the app.
// Here we are grabbing what is in local storage
$rootScope.currentUser = user;
if(toState.name === "login.signin") {
// go to the application "dashboard" state
$state.go('app.dashboard');
// Preventing the default behavior allows us to use $state.go
// to change states
event.preventDefault();
}
}
});