0

我想我可以尝试使用ui-router与角2保护的意见,验证或canActivate对角2 UI路由器

目前,我已经有了一些默认angular2-router配置,这主要归结为类似:

export const homeRoute: Route = { 
    path: '', 
    component: HomeComponent, 
    canActivate: [AuthGuard] 
}; 

ui-router文档示出了一个类似的例子,docs

export let state1: Ng2StateDeclaration = { 
    name: 'state1', 
    component: State1Component, 
    url: '/one' 
} 

其中W应该做得很好,但一个缺失的关键:canActivate

在角1我已经使用了一个伟大的lib:angular-permission但它不适用于角2.

我不此刻需要花哨的权限,一个简单的真/假认证会做,但是,我根本不知道如何保护我的路线。

我尝试过搜索,但主题太新鲜了,没有可用的示例。

感谢所有的想法。

回答

2

我相信您需要使用TransitionService.onBefore(),如API doc中所述。这个类是ui-router-core包的一部分角1 & 2之间共享它是在角1

简而言之直接替换的$transitions,使用

TransitionService.onBefore({to: 'requiresAuth.*'}, (transition: Transition) => { 
    let auth = transition.injector().get(YourOwnAuthService); 
    if (!auth.isLoggedIn()) { 
     return transition.router.stateService.target('login'); 
    } 
    return true; 
}); 

一个可以提取回调至function checkAuthentication(transition: Transition): boolean和将此函数应用于多个基本状态。例如,

['dashboard.*', 'report.*', 'sale.*'].forEach(state => { 
    TransitionService.onBefore({to: state}, checkAuthentication); 
}); 

此代码片段可以放置在您的UI路由器状态定义的正下方。

0

我想为您提供一个实现这一点的PoC应用程序。请直接从Github上找到它,因为代码可能对于消息框太多了。

LoggedInGuard(” /app/shared/guards/logged-in.guard.ts “) https://github.com/AFigueroa/angular2-poc/blob/master/app/shared/guards/logged-in.guard.ts

AppRoutingModule(” /app/app-routing.module.ts “) https://github.com/AFigueroa/angular2-poc/blob/master/app/app-routing.module.ts

+0

但它使用本地'angular2-router',我需要为'UI-router' – Atais

+0

所以只是想了解你的问题的解决方案,你需要一种方法来阻止,如果用户的登录访问gedIn值设置为false,在AngularJS(v1)上使用ui-router? –