如果用户已经在 Angular 4 中登录,如何限制对登录路由的访问?

How to restrict access to Login Route if user is already logged in in Angular 4?

我已成功实施 AuthGuardService,如果用户未登录,它会限制对受保护路由的访问。

我想要实现的是,如果用户已经登录并访问登录路由,我希望它重定向到另一个路由,如主页。

您可以在需要用户登录的路径上使用 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;
  }
}

您可以像这样在登录组件的 ngOnInit 中执行简单检查,如果它们已经通过身份验证,则重定向到您选择的另一个页面:

ngOnInit() {
   if (this._authService.isLoggedIn) {
      this._router.navigate(['/apps']);
   }
}

这对我有用!

您可以创建两个 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
        }
    }
}

在应用模块中注册 AuthGuard

...
providers:[AuthGuard,LoggedInAuthGuard]
...

在路由模块中添加AuthGuard

const routes: Route[] = [
  { path: "/login", component: LoginComponent, canActivate:[LoggedInAuthGuard] },
  { path: "/dashboard, component: DashboardComponent, canActivate: [AuthGuard]}
]