Angular redirect to login page

后端 未结 7 2240
盖世英雄少女心
盖世英雄少女心 2020-11-27 09:39

I come from the Asp.Net MVC world where users trying to access a page they are not authorized are automatically redirected to the login page.

I am trying to reproduc

7条回答
  •  情话喂你
    2020-11-27 09:52

    Following the awesome answers above I would also like to CanActivateChild: guarding child routes. It can be used to add guard to children routes helpful for cases like ACLs

    It goes like this

    src/app/auth-guard.service.ts (excerpt)

    import { Injectable }       from '@angular/core';
    import {
      CanActivate, Router,
      ActivatedRouteSnapshot,
      RouterStateSnapshot,
      CanActivateChild
    }                           from '@angular/router';
    import { AuthService }      from './auth.service';
    
    @Injectable()
    export class AuthGuard implements CanActivate, CanActivateChild {
      constructor(private authService: AuthService, private router:     Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state:    RouterStateSnapshot): boolean {
        let url: string = state.url;
        return this.checkLogin(url);
      }
    
      canActivateChild(route: ActivatedRouteSnapshot, state:  RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
      }
    
    /* . . . */
    }
    

    src/app/admin/admin-routing.module.ts (excerpt)

    const adminRoutes: Routes = [
      {
        path: 'admin',
        component: AdminComponent,
        canActivate: [AuthGuard],
        children: [
          {
            path: '',
            canActivateChild: [AuthGuard],
            children: [
              { path: 'crises', component: ManageCrisesComponent },
              { path: 'heroes', component: ManageHeroesComponent },
              { path: '', component: AdminDashboardComponent }
            ]
          }
        ]
      }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forChild(adminRoutes)
      ],
      exports: [
        RouterModule
      ]
    })
    export class AdminRoutingModule {}
    

    This is taken from https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard

提交回复
热议问题