Redirect to a different component inside @CanActivate in Angular2

前端 未结 6 569
攒了一身酷
攒了一身酷 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:33

    As of Angular 7.1, you can return UrlTree instead of boolean:

    @Injectable({
      providedIn: 'root',
    })
    export class AuthGuard implements CanActivate {
    
      constructor(private authService: AuthService, private router: Router) { }
    
      canActivate(): boolean | UrlTree {
        return this.authService.isAuthenticated() || this.router.createUrlTree(['/login']);
      }
    }
    

提交回复
热议问题