2017-01-23 54 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