src/app/auth/auth.guard.ts
Methods |
|
constructor(authService: AuthService, router: Router, cookie: CookieService)
|
||||||||||||
Defined in src/app/auth/auth.guard.ts:10
|
||||||||||||
Parameters :
|
canActivate | |||||||||
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
|
|||||||||
Defined in src/app/auth/auth.guard.ts:21
|
|||||||||
Parameters :
Returns :
Observable | Promise | boolean | UrlTree
|
Public canActivateChild | |||||||||
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot)
|
|||||||||
Defined in src/app/auth/auth.guard.ts:14
|
|||||||||
Parameters :
Returns :
boolean | UrlTree | Observable | Promise
|
Public checkLogin | ||||||
checkLogin(url: string)
|
||||||
Defined in src/app/auth/auth.guard.ts:29
|
||||||
Parameters :
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;
}
}