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? –