auth.guard.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { Injectable } from "@angular/core";
  2. import {
  3. CanActivate,
  4. ActivatedRouteSnapshot,
  5. RouterStateSnapshot,
  6. } from "@angular/router";
  7. import { Observable } from "rxjs";
  8. import { Router } from "@angular/router";
  9. import { AuthServr } from "./auth.service";
  10. import Parse from "parse";
  11. @Injectable({
  12. providedIn: "root",
  13. })
  14. export class AuthGuard implements CanActivate {
  15. LoginPage = "/user/login";
  16. constructor(public authService: AuthServr, public router: Router) {}
  17. canActivate(
  18. next: ActivatedRouteSnapshot,
  19. state: RouterStateSnapshot
  20. ): Observable<boolean> | Promise<boolean> | boolean {
  21. // 当前路由url
  22. let url: string = state.url;
  23. return this.checkLogin(url);
  24. }
  25. checkLogin(url: string): boolean {
  26. // 如果已登录,直接跳转当前路由 跳出该函数
  27. let currentUser = Parse.User.current();
  28. if (currentUser && currentUser.id) {
  29. return true;
  30. }
  31. // 否则重定向到login页面
  32. this.authService.redirectUrl = url;
  33. this.router.navigate([this.LoginPage]);
  34. return false;
  35. }
  36. }
  37. export { CanActivate };