File

src/app/auth/auth.guard.ts

Index

Methods

Constructor

constructor(authService: AuthService, router: Router, cookie: CookieService)
Parameters :
Name Type Optional
authService AuthService No
router Router No
cookie CookieService No

Methods

canActivate
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
Parameters :
Name Type Optional
route ActivatedRouteSnapshot No
state RouterStateSnapshot No
Returns : Observable | Promise | boolean | UrlTree
Public canActivateChild
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot)
Parameters :
Name Type Optional
childRoute ActivatedRouteSnapshot No
state RouterStateSnapshot No
Returns : boolean | UrlTree | Observable | Promise
Public checkLogin
checkLogin(url: string)
Parameters :
Name Type Optional
url string No
Returns : boolean
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivateChild, CanActivate {

  constructor(private authService: AuthService, private router: Router, private cookie: CookieService) { }

  public canActivateChild(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
    const url: string = state.url;
    return this.checkLogin(url);
  }

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    const url: string = state.url;
    return this.checkLogin(url);
  }

  public checkLogin(url: string): boolean {
    // 检查cookie中的登录状态
    const user = this.cookie.get('user');
    if (user) {
      this.authService.user = JSON.parse(user);
      this.authService.isLoggedIn = true;
    }
    // 登录则返回true
    if (this.authService.isLoggedIn) { return true; }
    // 保存登录前的url
    this.authService.redirectUrl = url;
    // 跳转到登录页面
    this.router.navigate(['/login']);
    return false;
  }

}

result-matching ""

    No results matching ""