import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) { } // 路由守卫 canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return this.checkLogin(); } checkLogin(): boolean { // 判断本地有没有token const token = sessionStorage.getItem('token'); // 如果有token,允许访问 if (token) { return true; } //如果没有token,跳转登录页 this.router.navigate(['/login']); return false; } }