我已经成功实现了 AuthGuardService,如果用户未登录,它会限制对受保护路由的访问。
我想要实现的是,如果用户已经登录并访问了登录路由,我希望它重定向到另一个路由,比如主页。
我已经成功实现了 AuthGuardService,如果用户未登录,它会限制对受保护路由的访问。
我想要实现的是,如果用户已经登录并访问了登录路由,我希望它重定向到另一个路由,比如主页。
您可以创建两个 CanActivate 守卫:
- 用于限制已登录用户的路由(例如:/login
等/register
)
- 用于限制未登录用户的路由(例如/dashboard
:)
loggedIn() {
//return boolean for loggedIn user logic
}
import { Injectable } from "@angular/core";
import { CanActivate, Router } from "@angular/router";
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _authService: AuthService, private _router: Router) { }
canActivate(): boolean {
if (this._authService.loggedIn()) {
return true;
} else {
this._router.navigate(['/login'])
return false
}
}
}
import { Injectable } from "@angular/core";
import { CanActivate, Router } from "@angular/router";
import { AuthService } from './auth.service';
@Injectable()
export class LoggedInAuthGuard implements CanActivate {
constructor(private _authService: AuthService, private _router: Router) { }
canActivate(): boolean {
if (this._authService.loggedIn()) {
this._router.navigate(['/dashboard'])
return false
} else {
return true
}
}
}
...
providers:[AuthGuard,LoggedInAuthGuard]
...
const routes: Route[] = [
{ path: "/login", component: LoginComponent, canActivate:[LoggedInAuthGuard] },
{ path: "/dashboard, component: DashboardComponent, canActivate: [AuthGuard]}
]
您可以像这样在登录组件的 ngOnInit 中执行简单的检查,如果它们已经通过身份验证,则重定向到您选择的另一个页面:
ngOnInit() {
if (this._authService.isLoggedIn) {
this._router.navigate(['/apps']);
}
}
这对我有用!
您可以在需要用户登录的路径上使用CanActivate 保护:
const ROUTER: Routes = [
{path: 'restricted', component: MyRestrictedCOmponent, canActivate:[LoginActivate]},
{path: 'home', component: HomeComponent},
];
以及在主页上重定向未登录用户的守卫:
@Injectable()
export class LoginActivate implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
if (!authService.isLoggedIn()) {
this.router.navigate(['home']);
}
return true;
}
}