9

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

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

4

3 回答 3

16

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

在 App Module 中注册 AuthGuard

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

在路由模块中添加 AuthGuard

const routes: Route[] = [
  { path: "/login", component: LoginComponent, canActivate:[LoggedInAuthGuard] },
  { path: "/dashboard, component: DashboardComponent, canActivate: [AuthGuard]}
]
于 2019-09-08T03:10:51.953 回答
7

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

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

这对我有用!

于 2017-11-03T08:06:24.307 回答
3

您可以在需要用户登录的路径上使用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;
  }
}
于 2017-11-02T14:29:10.270 回答