angularjs – locationChangeStart并阻止路由更改
发布时间:2020-12-17 10:21:46 所属栏目:安全 来源:网络整理
导读:我正在尝试创建基本验证,无论用户是否可以访问某些路由. 我在这方面取得了进展,但有一点我无法弄清楚. 我正在使用$locationChangeStart来监控路由更改.场景是: 1.如果用户已登录,则允许他访问除auth路由(登录,注册)之外的所有路由.我正在通过从我的AuthFact
我正在尝试创建基本验证,无论用户是否可以访问某些路由.
我在这方面取得了进展,但有一点我无法弄清楚. 我正在使用$locationChangeStart来监控路由更改.场景是: $rootScope.$on('$locationChangeStart',function(event,newUrl,oldUrl){ if(AuthFactory.isAuthenticated()){ if(AuthFactory.isAuthRoute(newUrl)){ event.preventDefault(); $location.path('/'); } } else { if(!AuthFactory.isAuthRoute(newUrl)){ event.preventDefault(); $location.path('/login'); } } }); 让我烦恼的是那个带有preventDefault()的人.如果应用程序到达带有preventDefault()的代码,之后的location.path()就行不通. 但是,如果我删除event.preventDefault(),location.path()工作.问题是,我需要阻止,以防非记录尝试访问某些非auth页面. 基本上,我希望能够根据请求的路线阻止或重定向.这样做的正确方法是什么?
好的,你需要这样做:
var authPreventer = $rootScope.$on('$locationChangeStart',oldUrl){ if(AuthFactory.isAuthenticated()){ if(AuthFactory.isAuthRoute(newUrl)){ event.preventDefault(); authPreventer(); //Stop listening for location changes $location.path('/'); } } else { if(!AuthFactory.isAuthRoute(newUrl)){ event.preventDefault(); authPreventer(); //Stop listening for location changes $location.path('/login'); } } }); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |