Angular8路由守衛(wèi)原理和使用方法
路由守衛(wèi)
守衛(wèi),顧名思義,必須滿足一定的條件得到許可方可通行,否則拒絕訪問或者重定向。Angular中路由守衛(wèi)可以借此處理一些權(quán)限問題,通常應(yīng)用中存儲(chǔ)了用戶登錄和用戶權(quán)限信息,遇到路由導(dǎo)航時(shí)會(huì)進(jìn)行驗(yàn)證是否可以跳轉(zhuǎn)。
4種守衛(wèi)類型
按照觸發(fā)順序依次為:canload(加載)、canActivate(進(jìn)入)、canActivateChild(進(jìn)入子路由)和canDeactivate(離開)。
一個(gè)所有守衛(wèi)都是通過的守衛(wèi)類:
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 {
// 權(quán)限控制邏輯如 是否登錄/擁有訪問權(quán)限
console.log('canActivate');
return true;
}
canDeactivate(
component: NewsComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot) {
console.log('canDeactivate');
return true;
}
canActivateChild() {
// 返回false則導(dǎo)航將失敗/取消
// 也可以寫入具體的業(yè)務(wù)邏輯
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 = [
// 一般情況很少需要同時(shí)寫多個(gè)守衛(wèi),如果有也是分開幾個(gè)文件(針對復(fù)雜場景,否則一般使用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: '參數(shù)錯(cuò)誤或者地址不存在'
}
},
{
path: '**',
redirectTo: 'error',
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
使用場景分析
1.canLoad
默認(rèn)值為true,表明路由是否可以被加載,一般不會(huì)認(rèn)為控制這個(gè)守衛(wèi)邏輯,99.99%情況下,默認(rèn)所有app模塊下路由均允許canLoad
2.canActivate
是否允許進(jìn)入該路由,此場景多為權(quán)限限制的情況下,比如客戶未登錄的情況下查詢某些資料頁面,在此方法中去判斷客戶是否登陸,如未登錄則強(qiáng)制導(dǎo)航到登陸頁或者提示無權(quán)限,即將返回等信息提示。
3.canActivateChild
是否可以導(dǎo)航子路由,同一個(gè)路由不會(huì)同時(shí)設(shè)置canActivate為true,canActivateChild為false的情況,此外,這個(gè)使用場景很苛刻,尤其是懶加載路由模式下,暫時(shí)未使用到設(shè)置為false的場景。
4.CanDeactivate
路由離開的時(shí)候進(jìn)行觸發(fā)的守衛(wèi),使用場景比較經(jīng)典,通常是某些頁面比如表單頁面填寫的內(nèi)容需要保存,客戶突然跳轉(zhuǎn)其它頁面或者瀏覽器點(diǎn)擊后退等改變地址的操作,可以在守衛(wèi)中增加彈窗提示用戶正在試圖離開當(dāng)前頁面,數(shù)據(jù)還未保存 等提示。
場景模擬
登錄判斷
前期準(zhǔn)備:login組件;配置login路由
因?yàn)閘ogin是獨(dú)立一個(gè)頁面,所以app.component.html應(yīng)該只會(huì)剩余一個(gè)路由導(dǎo)航
<!-- NG-ZORRO --> <router-outlet></router-outlet>
取而代之的是pages.component.html頁面中要加入header和footer部分變?yōu)槿缦拢?/p>
<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 = [
// 一般情況很少需要同時(shí)寫多個(gè)守衛(wèi),如果有也是分開幾個(gè)文件(針對復(fù)雜場景,否則一般使用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: '參數(shù)錯(cuò)誤或者地址不存在'
}
},
{
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: '關(guān)于我們'
}
},
{
path: 'contact',
component: ContactComponent,
data: {
title: '聯(lián)系我們'
}
},
{
path: 'news',
canDeactivate: [AuthGuard],
loadChildren: () => import('../component/news/news.module').then(m => m.NewsModule)
},
]
瀏覽器截圖:

明明我們的html寫了頭部和底部組件卻沒顯示?
路由的本質(zhì):根據(jù)配置的path路徑去加載組件或者模塊,此處我們是懶加載了路由,根據(jù)路由模塊再去加載不同組件,唯獨(dú)缺少了加載了pages組件,其實(shí)理解整個(gè)并不難,index.html中有個(gè)<app-root></app-root>,這就表明app組件被直接插入了dom中,反觀pages組件,根本不存在直接插進(jìn)dom的情況,所以這個(gè)組件根本沒被加載,驗(yàn)證我們的猜想很簡單:
export class PagesComponent implements OnInit {
constructor() { }
ngOnInit() {
alert();
}
}
經(jīng)過刷新頁面,alert()窗口并沒有出現(xiàn)~,可想而知,直接通過路由模塊去加載了對應(yīng)組件;其實(shí)我們想要的效果就是之前改造前的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: '關(guān)于我們'
}
},
{
path: 'contact',
component: ContactComponent,
data: {
title: '聯(lián)系我們'
}
},
{
path: 'news',
canDeactivate: [AuthGuard],
loadChildren: () => import('../component/news/news.module').then(m => m.NewsModule)
},
]
}
];

這樣寫,pages組件就被加載了,重回正題,差點(diǎn)回不來,我們在登錄組件中寫了簡單的登錄邏輯:
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');
}
}
}
守衛(wèi)中:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// 權(quán)限控制邏輯如 是否登錄/擁有訪問權(quán)限
console.log('canActivate', route);
const isLogin = window.localStorage.getItem('loginfo') ? true : false;
if (!isLogin) {
console.log('login');
this.router.navigateByUrl('login');
}
return true;
}

路由離開(選定應(yīng)用的組件是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: '聯(lián)系我們'
}
}
pageLeave(): Observable<boolean> {
return new Observable(ob => {
if (!this.isSaven) {
this.modal.warning({
nzTitle: '正在離開,是否需要保存改動(dòng)的數(shù)據(jù)?',
nzOnOk: () => {
// 保存數(shù)據(jù)
ob.next(false);
alert('is saving');
this.isSaven = true;
},
nzCancelText: '取消',
nzOnCancel: () => {
ob.next(true);
}
});
} else {
ob.next(true);
}
});
}
默認(rèn)數(shù)據(jù)狀態(tài)時(shí)未保存,可以選擇不保存直接跳轉(zhuǎn)也可以保存之后再跳轉(zhuǎn)。

此場景多用于復(fù)雜表單頁或者一些填寫資料步驟的過程中,甚至瀏覽器后退和前進(jìn)的操作也會(huì)觸發(fā)這個(gè)守衛(wèi),唯一不足的地方時(shí)這個(gè)守衛(wèi)綁定的是單一頁面,無法統(tǒng)一對多個(gè)頁面進(jìn)行攔截。
下一篇介紹路由事件的運(yùn)用。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。
相關(guān)文章
Angular應(yīng)用打包和部署實(shí)現(xiàn)過程詳解
這篇文章主要為大家介紹了Angular應(yīng)用打包和部署實(shí)現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
AngulaJS路由 ui-router 傳參實(shí)例
本篇文章主要介紹了AngulaJS路由 ui-router 傳參實(shí)例 ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04
Angular模版驅(qū)動(dòng)表單的使用總結(jié)
這篇文章主要介紹了Angular模版驅(qū)動(dòng)表單的使用總結(jié),本文實(shí)現(xiàn)了Angular支持表單的雙向數(shù)據(jù)綁定,校驗(yàn),狀態(tài)管理,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-05-05
Angular實(shí)現(xiàn)的內(nèi)置過濾器orderBy排序與模糊查詢功能示例
這篇文章主要介紹了Angular實(shí)現(xiàn)的內(nèi)置過濾器orderBy排序與模糊查詢功能,涉及AngularJS過濾器、排序及字符串遍歷、查詢等相關(guān)操作技巧,需要的朋友可以參考下2017-12-12
AngularJS使用ng-app自動(dòng)加載bootstrap框架問題分析
這篇文章主要介紹了AngularJS使用ng-app自動(dòng)加載bootstrap框架問題,分析了前面文章中所述的ng-app自動(dòng)加載bootstrap出現(xiàn)的錯(cuò)誤原因與相應(yīng)的解決方法,需要的朋友可以參考下2017-01-01
Angular中$cacheFactory的作用和用法實(shí)例詳解
$cacheFactory是一個(gè)為Angular服務(wù)生產(chǎn)緩存對象的服務(wù)。接下來通過本文給大家介紹Angular中$cacheFactory的作用和用法實(shí)例詳解,非常不錯(cuò),感興趣的朋友一起看下吧2016-08-08

