我正在使用angularjs和ui-router构建一个简单的博客应用程序,我想监听每个状态更改并检查用户是否已登录.如果他不是,我想将他重定向到登录页面.
这个场景非常简单,我试图在没有运气的情况下实现这个解决方案.
这是相关代码:
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'是我的主要供稿的网址,我希望该应用程序将在启动时进入.
在查看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.(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".
它出现了好几次.此外 - 网址在/ login和/ blogs之间跳转.
我究竟做错了什么?
(编辑:我在console.log中添加了一些调试)
出于某种原因,此代码有效:
app.run(function($rootScope, $state, $location, UserService){ $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ let loggedIn = UserService.isLoggedIn(); if (toState.name !== 'app.login' && !loggedIn){ $location.url('/login'); } }); });
我改变了从$ state.go到 $ location.url重定向到登录页面的方式.
每次我使用$state.go
它都会引发另一个$stateChangeStart
事件,这显然是错误的.这样event.preventDefault()
就没有必要了.