2017-01-23 60 views
0

路線PARAM我有路由配置如何解決在角2

const appRoutes: Routes = [ 
    { path: '', loadChildren: 'app/+home/home.module#HomeModule' }, 
    { path: 'auth', loadChildren: 'app/+auth/auth.module#AuthModule' }, 
    { path: ':category', loadChildren: 'app/+search/search.module#SearchModule' }, 
    { 
    path: '**', 
    component: PageNotFoundComponent, 
    data: { title: 'Page not found' } 
    }, 
]; 

我需要檢查,如果:category路線參數值的方式在數據庫中搜索類別存在,如果是激活路徑,否則到404頁(在這種情況下,PageNotFoundComponent)。

使用CanActivate是最好的方法嗎?如何導航到404頁面?

+1

您可能正在尋找警衛https://angular.io/docs/ts/latest/guide/router.html#!#guards –

回答

1

是的,你可以使用CanActivate後衛。

{ 
    path: ':category', 
    loadChildren: 'app/+search/search.module#SearchModule' 
    canActivate: [CanActivateCategory] 
}, 

然後執行重定向的防護罩內:

@Injectable() 
class CanActivateCategory implements CanActivate { 

    constructor(private router: Router, 
       private categoryService: CategoryService) {} 

    canActivate(
    route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
): Observable<boolean>|Promise<boolean>|boolean { 
    const obs = this.categoryService.categoryExists(route.params['category']); 
    obs.subscribe((exists: boolean) => { 
     if (!exists) this.router.navigate('/404'); 
    }); 
    return obs; 
    } 
} 

此代碼假定你有一個CategoryService驗證類別的存在,並且已經宣佈的路徑/404路線。

最後說明:如果您需要預先加載當前的一些數據:category,我會把這個代碼放在Resolve。這樣,您可以在一個位置完成所有操作:預加載數據,或者如果無法找到/預加載數據,請重定向至/404

+0

所以我需要從'**'更改404路由路徑到'404' ? – neilhem

+1

啊,我錯過了代碼中的'**'路由。那麼,如果你想能夠明確地將用戶重定向到「未找到」頁面,那麼最好有一個像'404'這樣的特定路徑。你可以用'redirectTo:'404''來保留'**'路線。 – AngularChef