当 canActivate 返回 false 时如何重定向另一个组件?

Moe*_*ini 5 routes angular angular5

您好,我正在 Angular 5 中使用路由,并且我有一个使用 canActivate 属性的登录路径

当 canActivate 为 false 时,我可以重定向到另一个路径吗?我不希望用户在登录后看到登录页面。

如果用户登录,这里主服务返回 false

{
    path: 'login',
    component: RegisterLoginComponent,
    canActivate: [MainService]
}
Run Code Online (Sandbox Code Playgroud)

小智 4

我认为更好的方法是使用Guard保护您的默认路径,并在身份验证失败时重定向到/login那里。

/* AuthService */
isLoggedIn(): boolean {
  // check if user is logged in
  return isUserLoggedIn;
}

/* AuthGuard */
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
...
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  // check if user is logged in
  const loggedIn: boolean = this.authService.isLoggedIn();
  // if not, redirect to /login
  if (!loggedIn) {
    this.router.navigate(['/login']);
  }
  return loggedIn;
}    
Run Code Online (Sandbox Code Playgroud)

注意:如果您想控制重定向到的位置,您可以访问用户尝试访问的 url route.url。您可以检查其值,然后导航到特定的 url,而不是始终导航到“/login”。

下面是一个快速示例代码,它也使用异步代码执行此重定向。https://stackblitz.com/edit/angular-async-guard-redirect?file=src%2Fapp%2Fauth-with-redirect.guard.ts