Angular Router CanActivate路由導航守衛

app資料夾新增 @guard 資料夾內新增 auth.guard.ts檔案中新增以下設定:
  • 引入 Injectableimport { Injectable } from '@angular/core';
  • 引入 ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTreeimport { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
  • 引入 Observable import { Observable } from 'rxjs';
  • class AuthGuard implements CanActivate 內
    constructor(private router: Router) { }
    canActivate( localStorage.getItem('token') 有登入並且沒有過期的jwt,沒有時,導到登入頁面 )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

//裝飾器
@Injectable({
providedIn: 'root'
})

export class AuthGuard implements CanActivate {

constructor(private router: Router) { }

canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

const jwt = localStorage.getItem('token');
if (jwt) {
const payload = JSON.parse(window.atob(jwt.split('.')[1]));
const exp = new Date(Number(payload.exp) * 1000);
if (new Date() > exp) {
alert('JWT已過期,請重新登入');
return this.router.createUrlTree(['/login']);
}
} else {
alert('尚未登入');
return this.router.createUrlTree(['/login']);
}
return true;
}

canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
return this.canActivate(childRoute, state);
}

}