2016-11-10 20 views
9

在Angular2中配置路線時,有沒有辦法設置「基地」canActivate?因此,所有路線都由相同的基本檢查覆蓋,然後每條路線可以進行更細粒度的檢查。在Angular 2應用程序中爲所有路線使用基地守衛

我有一個AppModule與路由這樣的:

@NgModule({ 
    imports: [ 
     RouterModule.forRoot([ 
      { 
       path: '', 
       component: HomeComponent, 
       canActivate: [AuthenticationGuardService], 
       data: { roles: [Roles.User] } 
      } 
     ]) 
    ], 
    exports: [ 
     RouterModule 
    ] 
}) 
export class AppRoutingModule { } 

並且功能模塊FeatureModule

@NgModule({ 
    imports: [ 
     RouterModule.forChild([ 
      { 
       path: "feature", 
       component: FeatureComponent, 

       // I'd like to avoid having to do this: 
       canActivate: [AuthenticationGuardService], 
       data: { roles: [Roles.User] } 
      } 
     ]) 
    ], 
    exports: [ 
     RouterModule 
    ] 
}) 
export class FeatureRoutingModule { } 

我讓AuthenticationGuardService檢查用戶是否具有使用角色訪問路線在data提供。

我可以做些什麼來避免在我所有的功能路由模塊中設置canActivatedata?我想在此應用程序中爲所有路線配置一個「基地」canActivate

+0

您可以從一個類或輔助函數來創建路由對象。這是最簡單的(也許是唯一可用的)解決方案。 – estus

+0

@estus所以你的意思是我應該這樣做:'RouterModule.forChild([helperService.getRoute(「feature」,FeatureComponent)])?然後,幫助器服務(或類或方法..)總是將基礎Guard添加到生成的路由對象中? – Joel

+2

是的。我會親自去'RouterModule.forChild([new AuthenticatedRoute({path:...,component:...})])' – estus

回答

7
const routes: Routes = [ 
    { 
    path: '', 
    canActivate: [AuthGuard], 
    children: [ 
     { path: '', component: HomeComponent }, 
     { path: 'builds', component: BuildsComponent }, 
     { path: 'files', component: FilesComponent }, 
     { path: 'publications', component: PublicationsComponent } 
    ] 
    }, 
    { path: 'login', component: LoginComponent }, 
    { path: '**', redirectTo: '' } 
]; 
+3

在工作的時候,這是不安全的,因爲通過'forChild'添加的子路由被添加爲'forRoot'路由的同胞,因此不在層次結構中,並且不會觸發警衛。 –

0

我寫了一個解決方案,動態添加保護我的應用程序的每一個途徑(包括那些由子模塊定義)。

我在閱讀this Router Docs時發現了這個解決方案。

const routes: Routes = [ 
 
    { path: '', redirectTo: 'home', pathMatch: 'full' }, 
 
    { path: 'login', component: LoginComponent, data: { skipGuard: true } }, 
 
    { path: '403', component: ForbiddenComponent, data: { skipGuard: true } }, 
 
    { path: '**', component: NotFoundComponent, data: { skipGuard: true } } 
 
]; 
 

 
@NgModule({ 
 
    imports: [RouterModule.forRoot(routes)], 
 
    exports: [RouterModule], 
 
    providers: [] 
 
}) 
 
export class AppRoutingModule { 
 
    
 
    constructor(router: Router) { 
 
    router.config 
 
     .filter(route => !route.data || !route.data.skipGuard) 
 
     .map(route => this.addGuard(route)); 
 
    } 
 
    
 
    private addGuard(route: Route): void { 
 
    route.canActivate = [AuthGuard].concat(route.canActivate); 
 
    route.canActivateChild = [AuthGuard].concat(route.canActivateChild); 
 
    } 
 
}

相關問題