路由守門員


說明

  1. 可藉由路由守門員(服務元件),設定能否進入(CanActive)某個路由頁面的條件與判斷
  2. 除了進入路由之外,也可用同樣的方式設定離開(CanDeactive)與讀取(CanLoad)路由頁面的判斷

程式碼寫法

路由守門員服務元件:

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";

@Injectable()
export class RouteGuard implements CanActivate {
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
    // 檢查的邏輯判斷
    let condition;
    if (condition) {
      // 條件符合,return true
      return true;
    } else {
      // 條件不符,return false
      return false;
    }
  }

}

路由模組內路由設定:

const routes: Routes = [
  {
    path: 'pathName/:params', 
    component: certainComponent,
    canActive: [RouteGuard] 
  }
]

程式碼範例:

1.建立RouteGuard服務元件

ng g class RouteGuard

2.在route-guard.ts中撰寫判斷條件:路由的id參數是否為"digiwin"

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {
  console.log(route.params["id"]);
  if (route.params["id"] == "digiwin") {
    return true;3
  }
  return false;
}

3.在app-routing.module.ts中變更路由設定如下

const routes: Routes = [
  ...
  {
    path: 'pageA',
    component: PageAComponent
  },
  ...
];

4.在app.module.ts內做RouteGuard的DI設定

@NgModule({
  ...
  providers: [RouteGuard],
  ...
})

5.點擊來去page-b連結,打開開發者工具看路由帶的id參數的值,並測試連結點下去是否能進入pageB

6.在網址列輸入localhost:4200/pageB/digiwin,測試能否進入pageB

results matching ""

    No results matching ""