AngularJS |处理路由他们之前加载 [英] AngularJS | handle routing before they load
问题描述
我要创造我的路线由外部服务的简单认证检查。
I wish to create a simple authentication check for my routes by external service.
我定义路由对象的访问要求:
I define the access requirements on the route object:
$routeProvider
.when('/', {
templateUrl: 'src/app/views/index.html',
controller: 'indexCtrl',
authenticated: true
})
.when('/login', {
templateUrl: 'src/app/views/login.html',
controller: 'loginCtrl',
anonymous: true
})
.otherwise({
redirectTo: '/'
})
;
然后,我检查,如果我有 $ routeChangeStart
事件中的权限。
$rootScope.$on('$routeChangeStart', function (event, next) {
if(next.authenticated && !$myService.isLoggedin())
$location.path("/login");
else if(next.anonymous && $myService.isLoggedin())
$location.path("/secured");
});
其实,这工程─
如果不是用户认证是他移动到登录页面,如果他被验证,但路线是为匿名用户只有它移动到其他页面,等等。
Actually, it works-
if the user in not authenticated it move him to the login page, if he is authenticated but the route is for anonymous users only it move them to another page, and etc..
按钮此重定向控制器和模板后实际发生的是负载!
它引起我的控制器做一些不必要的请求,我的REST API,即使我没有通过认证。
BUT- this redirection actually happening after the controllers and the templates is load! And it cause my controller to do some unnecessary request to my REST API, even if I'm not authenticated.
我该如何处理它们的路由过程之前?
How can I handle the route before they process?
推荐答案
我的解决方案是结合 $ locationChangeStart
和 $ routeChangeStart
:
My solution was combining $locationChangeStart
and $routeChangeStart
:
$rootScope.$on('$locationChangeStart', function (event) {
//If login data not available, make sure we request for it
if($facebook.isConnected()==null) {
$facebook.getLoginStatus();
event.preventDefault();
return;
}
var next=parseRoute().$$route;
if(!Auth.loginCheck(next))
event.preventDefault();
});
我复制 parseRoute()
从角route.js
来解析给定的URL路由..
I copied parseRoute()
from angular-route.js
to parse the given URL to route..
然后我建立我的登录校验处理器( Auth.loginCheck
)的方式,如果失败就返回false。
Then I build my login check handler(Auth.loginCheck
) in a way that if it fail it return false.
我也用 $ routeChangeStart
来处理 $ route.reload()
事件,所以现在在每次更改后我的认证状态我只是做 $ route.reload()
:
I also use $routeChangeStart
to handle $route.reload()
events, so now after every change within my authentication status I just do $route.reload()
:
$rootScope.$on('$routeChangeStart', function (event, next) {
Auth.loginCheck(next);
});
最后,我只是确保该定制服务始终将通过使用简单的运行的run()
方法。
我们现在使用的ngAuth,我们设计来解决这个确切的问题一个模块(基于我以前给这里的答案)。
We now using ngAuth, a module we designed to solve that exact problem(based on the answer I gave here before).
最后,我们开发了一个角模块,解决了这个问题。这个模块是基于我以前在这里发表了答案。
At last, we developed a angular-module that solved this issue.. This module is based on the answer I published here before.
由于这里的要求,我们发表了beta版本的作品现在: http://github.com/GoDisco/ngAuth
Due the requests here, we published a beta release that works now: http://github.com/GoDisco/ngAuth
随意使用它。
这篇关于AngularJS |处理路由他们之前加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!