我试图阻止所有的ui路由器状态更改,直到我验证了用户:
$rootScope.$on('$stateChangeStart',function (event,next,toParams) { if (!authenticated) { event.preventDefault() //following $timeout is emulating a backend $http.get('/auth/') request $timeout(function() { authenticated = true $state.go(next,toParams) },1000) } })
我拒绝所有的状态改变,直到用户被认证,但是如果我去一个使用else()配置的无效URL,我得到一个无限循环与一个消息:
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"]]
以下是我的SSCCE.使用python -m SimpleHTTPServer 7070进行操作,并转到localhost:7070 / test.html#/ bar,看到它在你的脸上爆炸。而直接导航到唯一有效的cornerjs位置不会吹灭localhost:7070 / test.html#/ foo:
<!doctype html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script> </head> <body ng-app="clientApp"> <div ui-view="" ></div> <script> var app = angular.module('clientApp',['ui.router']) var myRouteProvider = [ '$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider) { $urlRouterProvider.otherwise('/foo'); $stateProvider.state('/foo',{ url: '/foo',template: '<div>In Foo now</div>',reloadOnSearch: false }) }] app.config(myRouteProvider) var authenticated = false app.run([ '$rootScope','$log','$state','$timeout',function ($rootScope,$log,$state,$timeout) { $rootScope.$on('$stateChangeStart',toParams) { if (!authenticated) { event.preventDefault() //following $timeout is emulating a backend $http.get('/auth/') request $timeout(function() { authenticated = true $state.go(next,toParams) },1000) } }) } ]) </script> </body> </html>
有没有一种替代方法我应该用来完成这种身份验证阻止?我确实认识到这种认证阻塞只是客户端。在这个例子中,我没有显示服务器端的东西。
当您使用$ urlRouterProvider.otherwise(“/ foo”)与$ stateChangeStart的组合时,看起来这是一个ui-router的错误。
问题 – https://github.com/angular-ui/ui-router/issues/600
Frank Wallis提供了一个很好的解决方法,使用以函数作为参数的其他方法的更长的形式:
$urlRouterProvider.otherwise( function($injector,$location) { var $state = $injector.get("$state"); $state.go("app.home"); });
尼斯工作弗兰克!