How to Redirect to a certain route based on condition in Angular 2.

谁都会走 提交于 2019-11-30 16:51:44

问题


I am creating one angular2-meteor app.

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
    }]
}];

When i login to my app using LoginComponent it will go to TemplateComponent which have three child components

  • dashboard
  • csvtimeline
  • csvjson

Now i have by default set redirectTo to my dashboard component. but in place of this redirect i want to redirect to csvjson component or csvtimeline component based on login user profile.

Suppose

If Login User is "Admin" he should be redirectTo - > dashboard Component

If Login User is "Guest" then he should be redirectTo - > csvjson component

i know we can do this in ngOnInit() of dashboard component for redirect.

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

but i am looking for better option so i don't have to open dashboard component each time and it will directly go to csvjson component.


回答1:


Here is the better solution Guard the admin feature according to Angular guide.
Using CanActivate hook Steps:

1) Add auth-guard.service.ts file

    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) Update the routing file, In my case its 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 { }

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




回答2:


In routing module, u need to create local variable "route",check condition and assign requires routing path the variable and assign variable to redirectTo in routing

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',
  }


来源:https://stackoverflow.com/questions/40933619/how-to-redirect-to-a-certain-route-based-on-condition-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!