Ami*_*mar 10 angular2-routing angular2-meteor angular
我正在创建一个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
}]
}];
Run Code Online (Sandbox Code Playgroud)
当我使用LoginComponent登录到我的应用程序时,它将转到具有三个子组件的TemplateComponent
现在,默认情况下,我将redirectTo设置为我的仪表板组件。但是我想根据登录用户配置文件重定向到csvjson组件或csvtimeline组件,以代替此重定向。
假设
如果登录用户是“管理员”,则应将其重定向到->仪表板组件
如果登录用户是“来宾”,则应该将其重定向到-> csvjson组件
我知道我们可以在仪表板组件的ngOnInit()中进行重定向。
if (this.user && this.user.profile.role == 'Guest') {
this._router.navigate(['csvtemplate/csvjson']);
}
Run Code Online (Sandbox Code Playgroud)
但是我正在寻找更好的选择,因此我不必每次都打开仪表板组件,它将直接转到csvjson组件。
小智 7
这是更好的解决方案,根据Angular指南保护管理员功能。
使用CanActivate挂钩
步骤:
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { Router } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
canActivate() {
//Your redirect logic/condition. I use this.
if (this.user && this.user.profile.role == 'Guest') {
this.router.navigate(['dashboard']);
}
console.log('AuthGuard#canActivate called');
return true;
}
//Constructor
constructor(private router: Router) { }
}
Run Code Online (Sandbox Code Playgroud)
import { AuthGuard } from './auth-guard.service';
import { AdminComponent } from './admin/admin.component';
@NgModule({
declarations: [
AppComponent,
AdminComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{
path: 'admin',
component: AdminComponent,
canActivate:[AuthGuard]
},
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
}
])
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
**参考** https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
| 归档时间: |
|
| 查看次数: |
12847 次 |
| 最近记录: |