国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Angular8路由守衛原理和使用方法

2019-11-19 10:56:39
字體:
來源:轉載
供稿:網友

路由守衛

守衛,顧名思義,必須滿足一定的條件得到許可方可通行,否則拒絕訪問或者重定向。Angular中路由守衛可以借此處理一些權限問題,通常應用中存儲了用戶登錄和用戶權限信息,遇到路由導航時會進行驗證是否可以跳轉。

4種守衛類型

按照觸發順序依次為:canload(加載)、canActivate(進入)、canActivateChild(進入子路由)和canDeactivate(離開)。

一個所有守衛都是通過的守衛類:

import { Injectable } from '@angular/core';import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild, CanLoad, CanDeactivate} from '@angular/router';import { Route } from '@angular/compiler/src/core';import { NewsComponent } from '../component/news/news.component';@Injectable({ providedIn: 'root' })export class AuthGuard implements CanActivate, CanActivateChild, CanLoad, CanDeactivate<any> { constructor(  private router: Router ) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {  // 權限控制邏輯如 是否登錄/擁有訪問權限  console.log('canActivate');  return true; } canDeactivate(  component: NewsComponent,  currentRoute: ActivatedRouteSnapshot,  currentState: RouterStateSnapshot,  nextState: RouterStateSnapshot) {  console.log('canDeactivate');  return true; } canActivateChild() {  // 返回false則導航將失敗/取消  // 也可以寫入具體的業務邏輯  console.log('canActivateChild');  return true; } canLoad(route: Route) {  // 是否可以加載路由  console.log('canload');  return true; }}

app-routing.module.ts

import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { ErrorComponent } from './error/error.component';import { AuthGuard } from './core/auth-guard';const routes: Routes = [ // 一般情況很少需要同時寫多個守衛,如果有也是分開幾個文件(針對復雜場景,否則一般使用canActivated足夠) {  path: '',  canLoad: [AuthGuard],  canActivate: [AuthGuard],  canActivateChild: [   AuthGuard  ],  canDeactivate: [AuthGuard],  loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) }, {  path: 'error',  component: ErrorComponent,  data: {   title: '參數錯誤或者地址不存在'  } }, {  path: '**',  redirectTo: 'error',  pathMatch: 'full' }];@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }

使用場景分析

1.canLoad

默認值為true,表明路由是否可以被加載,一般不會認為控制這個守衛邏輯,99.99%情況下,默認所有app模塊下路由均允許canLoad

2.canActivate

是否允許進入該路由,此場景多為權限限制的情況下,比如客戶未登錄的情況下查詢某些資料頁面,在此方法中去判斷客戶是否登陸,如未登錄則強制導航到登陸頁或者提示無權限,即將返回等信息提示。

3.canActivateChild

是否可以導航子路由,同一個路由不會同時設置canActivate為true,canActivateChild為false的情況,此外,這個使用場景很苛刻,尤其是懶加載路由模式下,暫時未使用到設置為false的場景。

4.CanDeactivate

路由離開的時候進行觸發的守衛,使用場景比較經典,通常是某些頁面比如表單頁面填寫的內容需要保存,客戶突然跳轉其它頁面或者瀏覽器點擊后退等改變地址的操作,可以在守衛中增加彈窗提示用戶正在試圖離開當前頁面,數據還未保存 等提示。

場景模擬

登錄判斷

前期準備:login組件;配置login路由

因為login是獨立一個頁面,所以app.component.html應該只會剩余一個路由導航

<!-- NG-ZORRO --><router-outlet></router-outlet>

取而代之的是pages.component.html頁面中要加入header和footer部分變為如下:

<app-header></app-header><div nz-row class="main"> <div nz-col nzSpan="24">  <router-outlet></router-outlet> </div></div><app-footer></app-footer>

app-routing.module.ts 中路由配置2種模式分析:

// 非懶加載模式import { NgModule } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { ErrorComponent } from './error/error.component';import { AuthGuard } from './core/auth-guard';import { LoginComponent } from './component/login/login.component';import { PagesComponent } from './pages/pages.component';import { IndexComponent } from './component/index/index.component';const routes: Routes = [ // 一般情況很少需要同時寫多個守衛,如果有也是分開幾個文件(針對復雜場景,否則一般使用canActivated足夠) {  path: '',  canLoad: [AuthGuard],  canActivate: [AuthGuard],  canActivateChild: [   AuthGuard  ],  canDeactivate: [AuthGuard],  component: PagesComponent,  children: [   {    path: 'index',    component: IndexComponent   }   // ...  ]  // loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) }, {  path: 'login',  component: LoginComponent,  data: {   title: '登錄'  } }, {  path: 'error',  component: ErrorComponent,  data: {   title: '參數錯誤或者地址不存在'  } }, {  path: '**',  redirectTo: 'error',  pathMatch: 'full' }];@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule]})export class AppRoutingModule { }

非懶加載模式下,想要pages組件能夠正常顯示切換的路由和固定頭部足部,路由只能像上述這樣配置,也就是所有組件都在app模塊中聲明,顯然不是很推薦這種模式,切換回懶加載模式:

{  path: '',  canLoad: [AuthGuard],  canActivate: [AuthGuard],  canActivateChild: [   AuthGuard  ],  canDeactivate: [AuthGuard],  loadChildren: () => import('./pages/pages.module').then(m => m.PagesModule) },

pages-routing.module.ts

初始模板:

const routes: Routes = [ {  path: '',  redirectTo: 'index',  pathMatch: 'full' }, {  path: 'index',  component: IndexComponent,  data: {   title: '公司主頁'  } }, {  path: 'about',  component: AboutComponent,  data: {   title: '關于我們'  } }, {  path: 'contact',  component: ContactComponent,  data: {   title: '聯系我們'  } }, {  path: 'news',  canDeactivate: [AuthGuard],  loadChildren: () => import('../component/news/news.module').then(m => m.NewsModule) },]

瀏覽器截圖:

明明我們的html寫了頭部和底部組件卻沒顯示?

路由的本質:根據配置的path路徑去加載組件或者模塊,此處我們是懶加載了路由,根據路由模塊再去加載不同組件,唯獨缺少了加載了pages組件,其實理解整個并不難,index.html中有個<app-root></app-root>,這就表明app組件被直接插入了dom中,反觀pages組件,根本不存在直接插進dom的情況,所以這個組件根本沒被加載,驗證我們的猜想很簡單:

export class PagesComponent implements OnInit { constructor() { } ngOnInit() {  alert(); }}

經過刷新頁面,alert()窗口并沒有出現~,可想而知,直接通過路由模塊去加載了對應組件;其實我們想要的效果就是之前改造前的app.component.html效果,所以路由配置要參照更改:

const routes: Routes = [ {  path: '',  component: PagesComponent,  children: [   {    path: '',    redirectTo: 'index',    pathMatch: 'full'   },   {    path: 'index',    component: IndexComponent,    data: {     title: '公司主頁'    }   },   {    path: 'about',    component: AboutComponent,    data: {     title: '關于我們'    }   },   {    path: 'contact',    component: ContactComponent,    data: {     title: '聯系我們'    }   },   {    path: 'news',    canDeactivate: [AuthGuard],    loadChildren: () => import('../component/news/news.module').then(m => m.NewsModule)   },  ] }];

這樣寫,pages組件就被加載了,重回正題,差點回不來,我們在登錄組件中寫了簡單的登錄邏輯:

import { Component, OnInit } from '@angular/core';import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';import { Router } from '@angular/router';@Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss']})export class LoginComponent implements OnInit { loginForm: FormGroup; constructor(  private fb: FormBuilder,  private router: Router ) { } ngOnInit() {  this.loginForm = this.fb.group({   loginName: ['', [Validators.required]],   password: ['', [Validators.required]]  });  console.log(this.loginForm); } loginSubmit(event, value) {  if (this.loginForm.valid) {   window.localStorage.setItem('loginfo', JSON.stringify(this.loginForm.value));   this.router.navigateByUrl('index');  } }}

守衛中:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {  // 權限控制邏輯如 是否登錄/擁有訪問權限  console.log('canActivate', route);  const isLogin = window.localStorage.getItem('loginfo') ? true : false;  if (!isLogin) {   console.log('login');   this.router.navigateByUrl('login');  }  return true; }

路由離開(選定應用的組件是contact組件):

canDeactivate(  component: ContactComponent,  currentRoute: ActivatedRouteSnapshot,  currentState: RouterStateSnapshot,  nextState: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {  console.log('canDeactivate');  return component.pageLeave(); }
{  path: 'contact',  canDeactivate: [AuthGuard],  component: ContactComponent,  data: {   title: '聯系我們'  } }
pageLeave(): Observable<boolean> {  return new Observable(ob => {   if (!this.isSaven) {    this.modal.warning({     nzTitle: '正在離開,是否需要保存改動的數據?',     nzOnOk: () => {      // 保存數據      ob.next(false);      alert('is saving');      this.isSaven = true;     },     nzCancelText: '取消',     nzOnCancel: () => {      ob.next(true);     }    });   } else {    ob.next(true);   }  }); }

默認數據狀態時未保存,可以選擇不保存直接跳轉也可以保存之后再跳轉。

此場景多用于復雜表單頁或者一些填寫資料步驟的過程中,甚至瀏覽器后退和前進的操作也會觸發這個守衛,唯一不足的地方時這個守衛綁定的是單一頁面,無法統一對多個頁面進行攔截。

下一篇介紹路由事件的運用。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林網的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 手游| 北川| 靖西县| 孝义市| 神木县| 辽源市| 海林市| 苏州市| 西乌珠穆沁旗| 五寨县| 太原市| 同德县| 崇州市| 东兰县| 乌兰浩特市| 婺源县| 中西区| 威海市| 商河县| 巴楚县| 正定县| 珠海市| 汉川市| 上蔡县| 时尚| 泰安市| 正安县| 文水县| 探索| 彰化市| 微博| 台湾省| 涪陵区| 炉霍县| 兴安县| 临清市| 中西区| 万安县| 贵南县| 滦平县| 布拖县|