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

后端 未结 2 1848
别跟我提以往
别跟我提以往 2021-01-01 16:17

I am creating one angular2-meteor app.

export const routes: Route[] = [{
    path: \'\',
    redirectTo: \"login\",
    pathMatch: \"full\"
}, 
{
    path:          


        
2条回答
  •  醉梦人生
    2021-01-01 17:09

    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 it's 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

提交回复
热议问题