2016-12-12 63 views
2

鑑於這個簡單的路由示例,我希望能夠限制:page參數。如何限制Angular2路由參數?

const appRoutes: Routes = [ 
    { path: ':page', component: PageFoundComponent }, 
    { path: '**', component: PageNotFoundComponent } 
]; 

最好帶有一串字符串。預期的行爲是檢查:page是否爲Array元素之一,如果不存在,則路由到PageNotFoundComponent

// pseudo code 
let knownPages = ["welcome", "shop", "about"]; 
(...) 
{ path: ':[email protected]', component: PageFoundComponent } 

這個概念是從Symfony2路由機制中借用來的。

我應該如何處理它?

回答

0

看你會希望使用路由器Guards。具體而言,可能是CanActivate Guard

import { AuthGuard }    from '../auth-guard.service'; 
 

 
const adminRoutes: Routes = [ 
 
    { 
 
    path: ':page', 
 
    component: Component, 
 
    canActivate: [AuthGuard] 
 
    } 
 
]; 
 

 
@NgModule({ 
 
    imports: [ 
 
    RouterModule.forChild(adminRoutes) 
 
    ], 
 
    exports: [ 
 
    RouterModule 
 
    ] 
 
}) 
 
export class RoutingModule {}

注意,您可以使用多個守衛。如果路徑位於數組中,則可以返回true,其中一個可能與身份驗證有關,一個可能與角色有關,等等。