繁体   English   中英

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

[英]How to redirect another component when canActivate returns false?

嗨我在angular 5中使用路由,我有一个使用canActivate属性的登录路径

当canActivate为false时,我可以重定向到另一个路径吗? 如果他/她已登录,我不希望用户看到登录页面。

如果用户已登录,则此主服务返回false

{
    path: 'login',
    component: RegisterLoginComponent,
    canActivate: [MainService]
}

我认为更好的方法是使用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;
}    

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

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

如果凭据匹配,则在登录服务中重定向

 this.authService.signin(user)
  .subscribe(
    data => {

      this.router.navigateByUrl('/dashboard');
    },
    error => console.error(error)
  )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM