[英]How not to show the login page for a logged in user in angular
我有一个身份验证模块,路由身份验证模块包含以下路由:
const authRoutes: Routes = [
{
path: 'sign-in', component: SignInComponent
}
];
仪表板路由模块包含以下路由:
const dashboardRoutes: Routes = [
{ path: 'home', component: HomeComponent, canActivate: [IsAuthenticatedGuard] }
];
app(根)路由模块包含以下路由配置:
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: '**', component: PageNotFoundComponent }
];
因此,当用户登录到根目录时,他们会被重定向到主页,当未登录时,他们最终会进入登录页面,这是所需的行为。 但是,当用户登录时,他们仍然可以 go 到登录页面,我认为,在这种情况下,将用户重定向到主页是有意义的,因为他们已登录并且不需要登录页面。
我不能在 IsAuthenticatedGuard 中执行此操作,因为如果我编写如下内容:
@Injectable({
providedIn: 'root'
})
export class IsAuthenticatedGuard implements CanActivate {
private isSignedIn: boolean = true;
constructor(
private router: Router
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.isSignedIn) {
// this.router.navigate(['home']);
return true;
} else {
this.router.navigate(['sign-in']);
return false;
}
}
}
注意注释掉的行,它会陷入一个非常明显的无限循环。 实现它的正确方法是什么?
编辑:
我现在能想到的解决方案是将重定向逻辑添加到登录组件,基本上是这样的:
ngOnInit() {
if (this.isSignedIn) {
this.router.navigate(['home']);
}
}
您可以定义一个守卫并添加到您的路线中,如下所示:
@Injectable()
export class IsSignedInGuard implements CanActivate {
// here you can inject your auth service to check that user is signed in or not
constructor(private authService: AuthService,private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isSignedIn()) {
this.router.navigate(["/"]); // or home
return false;
}
return true;
}
}
然后在您的路由中:
const authRoutes: Routes = [
{
path: 'sign-in', component: SignInComponent , canActivate: [IsSignedInGuard]
}
];
注意:你不需要检查 ngOnInit 钩子;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.