如何根据Angular 2中的条件重定向到某个路径。

时间:2016-12-02 13:43:13

标签: angular angular2-routing angular2-meteor

我正在创建一个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组件来代替此重定向。

假设

如果登录用户是&#34;管理员&#34;他应该重定向到 - &gt;仪表板组件

如果登录用户是&#34;访客&#34;然后他应该重定向到 - &gt; csvjson组件

我知道我们可以在仪表板组件的ngOnInit()中进行重定向。

if (this.user && this.user.profile.role == 'Guest') {
             this._router.navigate(['csvtemplate/csvjson']);
        }

但我正在寻找更好的选择,所以我不必每次都打开仪表板组件,它将直接转到csvjson组件。

2 个答案:

答案 0 :(得分:4)

根据Angular指南,这是更好的解决方案保护管理功能 使用CanActivate hook 步骤进行:

1)添加auth-guard.service.ts文件

    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) { }
    }

2)更新路由文件,在我的例子中是app.module.ts

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 { }

**参考** https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

答案 1 :(得分:0)

在路由模块中,你需要创建局部变量&#34; route&#34 ;,检查条件并分配需要路由路径的变量 并在路由

中将变量赋值给redirectTo
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

var route: string = "user";
const role = JSON.parse(localStorage.getItem("currentUser")).roleId;

if (role == "1") {
//superadmin role
 route = "project"
} else {
  //normal user role
  route = "user"
}
const adminRoutes: Routes = [ {
path: '',
component: AdminComponent,
canActivate: [AuthGuard],
children: [

  { path: '', redirectTo: route },
  {
    path: 'project',
    loadChildren: './project-dashboard/project-dashboard.module#ProjectModule'
  }, {
    path: 'user',
    loadChildren: './user/user.module#UserModule',
  }