我正在使用angularjs和ui-router构建一个简单的博客应用程序,我想监听每个状态变化并检查用户是否已登录。如果他没有登录,我想将他重定向到登录页面。
场景非常简单,我试图实现this solution,但没有成功。
以下是相关代码:
场景非常简单,我试图实现this solution,但没有成功。
以下是相关代码:
app.config(function($stateProvider, $urlRouterProvider){
$stateProvider.state('app', {
url: '',
abstract: true
});
$urlRouterProvider.otherwise('blogs');
});
app.run(function($rootScope, $state, $location, UserService){
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
console.log("state change: from state: " + fromState.name + " to state: " + toState.name);
let loggedIn = UserService.isLoggedIn();
if (toState.name !== 'app.login' && !loggedIn){
event.preventDefault();
$state.go('app.login');
});
});
在这里,'app.login'被定义为登录状态,而'blogs'是我想要应用程序在启动时访问的主要源的URL。
当没有用户登录时,在Chrome控制台中查看时,我看到:
[HMR] Waiting for update signal from WDS...
state change: from state: to state: app.blogs
state change: from state: to state: app.login
state change: from state: to state: app.blogs
state change: from state: to state: app.login
state change: from state: to state: app.blogs
state change: from state: to state: app.login
state change: from state: to state: app.blogs
state change: from state: to state: app.login
state change: from state: to state: app.blogs
state change: from state: to state: app.login
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.5/$rootScope/infdig?p0=10&p1=%5B%5D
at REGEX_STRING_REGEXP (angular.js:68)
at Scope.$get.Scope.$digest (angular.js:15753)
at Scope.$get.Scope.$apply (angular.js:15986)
at bootstrapApply (angular.js:1658)
at Object.invoke (angular.js:4473)
at doBootstrap (angular.js:1656)
at Object.bootstrap (angular.js:1676)
at Object.<anonymous> (bootstrap.js:4)
at __webpack_require__ (bootstrap 7b71f5eb02d2540fe63f:520)
at fn (bootstrap 7b71f5eb02d2540fe63f:75)
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.4.5/$rootScope/infdig?p0=10&p1=%5B%5D
XHR finished loading: GET "http://localhost:8080/login/login.html".
这个问题好像出现了好几次。而且,URL 在 /login 和 /blogs 之间跳转。
我做错了什么?
(编辑:我在 console.log 中添加了一些调试信息)