import { Injectable } from "@angular/core"; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, } from "@angular/router"; import { Observable } from "rxjs"; import { Router } from "@angular/router"; import { AuthServr } from "./auth.service"; import Parse from "parse"; @Injectable({ providedIn: "root", }) export class AuthGuard implements CanActivate { LoginPage = "/user/login"; constructor(public authService: AuthServr, public router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable | Promise | boolean { // 当前路由url let url: string = state.url; return this.checkLogin(url); } checkLogin(url: string): boolean { // 如果已登录,直接跳转当前路由 跳出该函数 let currentUser = Parse.User.current(); if (currentUser && currentUser.id) { return true; } // 否则重定向到login页面 this.authService.redirectUrl = url; this.router.navigate([this.LoginPage]); return false; } } export { CanActivate };