我正在创建一个angular2-meteor应用程序 .
export const routes: Route[] = [{
path: '',
redirectTo: "login",
pathMatch: "full"
},
{
path: 'login',
component: LoginComponent
},
{
path: 'csvtemplate',
component: TemplateComponent,
canActivate: ['canActivateForLoggedIn'],
children: [{
path: '',
redirectTo: 'dashboard' <----how to add condition for multiple path
},
{
path:'dashboard',
component: DashboardComponent
},
{
path: 'csvtimeline/:month/:year',
component: CsvTimelineComponent
}, {
path: 'csvjson',
component: CsvJsonComponent
}]
}];
当我使用LoginComponent登录我的应用程序时,它将转到具有三个子组件的TemplateComponent
-
仪表板
-
csvtimeline
-
csvjson
现在我默认将redirectTo设置为我的仪表板组件 . 但是,我希望根据登录用户配置文件重定向到csvjson组件或csvtimeline组件,而不是此重定向 .
假设
If Login User is "Admin" he should be redirectTo - > dashboard Component
If Login User is "Guest" then he should be redirectTo - > csvjson component
我知道我们可以在仪表板组件的ngOnInit()中进行重定向 .
if (this.user && this.user.profile.role == 'Guest') {
this._router.navigate(['csvtemplate/csvjson']);
}
但我正在寻找更好的选择,所以我不必每次都打开仪表板组件,它将直接转到csvjson组件 .
2 回答
根据Angular指南,这是更好的解决方案 Guard the admin feature .
Using CanActivate hook 步骤:
1)添加auth-guard.service.ts文件
2)更新路由文件,在我的例子中是app.module.ts
参考 https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
在路由模块中,你需要创建局部变量“route”,检查条件并分配需要路由路径的变量和赋值变量到redirectTo路由