Redirect to a different component inside @CanActivate in Angular2

前端 未结 6 557
攒了一身酷
攒了一身酷 2020-12-03 10:03

Is there any way we can redirect to a different component from @CanActivate in Angular2 ?

6条回答
  •  情深已故
    2020-12-03 10:30

    Your guard can easily just be an injectable which, as such, can include its own injectables. So we can simply inject the router, in order to redirect. Don't forget to add the service as a provider in your app module.

    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private router: Router, private authService: AuthService) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean {
        if (!authService.isAuthenticated()) {
          this.router.navigate(['/login']);
          return false;
        }
        return true;
      }
    }
    
    export const ROUTES: Routes = [
      {path: 'login', component: LoginComponent},
      {path: 'protected', loadChildren: 'DashboardComponent', canActivate: [AuthGuard]}
    ];
    

提交回复
热议问题