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

时间:2017-11-02 14:22:01

标签: angular angular4-router

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

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

3 个答案:

答案 0 :(得分:3)

您可以像这样对登录组件的ngOnInit执行简单检查,如果已经过身份验证,则会重定向到您选择的其他页面:

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

这对我有用!

答案 1 :(得分:2)

您可以在需要用户登录的路径上使用 CanActivate guard

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;
  }
}

答案 2 :(得分:1)

您可以创建两个CanActivate防护:
 -用于限制已登录用户的路由(例如: $p2 = json_decode($_GET['form_ele1'], true); $p4 = array(); foreach($p2 as $key => $value){ $tkey = $key; parse_str($tkey, $arr); foreach($arr as $key2 => $value2){ $p4[$key2][key($value2)] = $value; } } $p2 = $p4; /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
        }
    }
}

在应用模块中注册AuthGuard

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]
...