欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular8路由守衛(wèi)原理和使用方法

 更新時間:2019年08月29日 09:46:18   作者:何棄療  
這篇文章主要給大家介紹了關(guān)于Angular8路由守衛(wèi)原理和使用方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用Angular8具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧

路由守衛(wèi)

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

4種守衛(wèi)類型

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

一個所有守衛(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 = [
 // 一般情況很少需要同時寫多個守衛(wèi),如果有也是分開幾個文件(針對復(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ù)錯誤或者地址不存在'
  }
 },
 {
  path: '**',
  redirectTo: 'error',
  pathMatch: 'full'
 }
];

@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

使用場景分析

1.canLoad

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

2.canActivate

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

3.canActivateChild

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

4.CanDeactivate

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

場景模擬

登錄判斷

前期準(zhǔn)備:login組件;配置login路由

因為login是獨立一個頁面,所以app.component.html應(yīng)該只會剩余一個路由導(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 = [
 // 一般情況很少需要同時寫多個守衛(wèi),如果有也是分開幾個文件(針對復(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ù)錯誤或者地址不存在'
  }
 },
 {
  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ù)路由模塊再去加載不同組件,唯獨缺少了加載了pages組件,其實理解整個并不難,index.html中有個<app-root></app-root>,這就表明app組件被直接插入了dom中,反觀pages組件,根本不存在直接插進dom的情況,所以這個組件根本沒被加載,驗證我們的猜想很簡單:

export class PagesComponent implements OnInit {

 constructor() { }

 ngOnInit() {
  alert();
 }

}

經(jīng)過刷新頁面,alert()窗口并沒有出現(xiàn)~,可想而知,直接通過路由模塊去加載了對應(yīng)組件;其實我們想要的效果就是之前改造前的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組件就被加載了,重回正題,差點回不來,我們在登錄組件中寫了簡單的登錄邏輯:

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: '正在離開,是否需要保存改動的數(shù)據(jù)?',
     nzOnOk: () => {
      // 保存數(shù)據(jù)
      ob.next(false);
      alert('is saving');
      this.isSaven = true;
     },
     nzCancelText: '取消',
     nzOnCancel: () => {
      ob.next(true);
     }
    });
   } else {
    ob.next(true);
   }
  });
 }

默認數(shù)據(jù)狀態(tài)時未保存,可以選擇不保存直接跳轉(zhuǎn)也可以保存之后再跳轉(zhuǎn)。

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

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

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。

相關(guān)文章

  • Angular應(yīng)用打包和部署實現(xiàn)過程詳解

    Angular應(yīng)用打包和部署實現(xiàn)過程詳解

    這篇文章主要為大家介紹了Angular應(yīng)用打包和部署實現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-08-08
  • AngulaJS路由 ui-router 傳參實例

    AngulaJS路由 ui-router 傳參實例

    本篇文章主要介紹了AngulaJS路由 ui-router 傳參實例 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • 淺談angular4生命周期鉤子

    淺談angular4生命周期鉤子

    本篇文章主要介紹了淺談angularr4生命周期鉤子,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • Angular模版驅(qū)動表單的使用總結(jié)

    Angular模版驅(qū)動表單的使用總結(jié)

    這篇文章主要介紹了Angular模版驅(qū)動表單的使用總結(jié),本文實現(xiàn)了Angular支持表單的雙向數(shù)據(jù)綁定,校驗,狀態(tài)管理,非常具有實用價值,需要的朋友可以參考下
    2018-05-05
  • Angular實現(xiàn)的內(nèi)置過濾器orderBy排序與模糊查詢功能示例

    Angular實現(xiàn)的內(nèi)置過濾器orderBy排序與模糊查詢功能示例

    這篇文章主要介紹了Angular實現(xiàn)的內(nèi)置過濾器orderBy排序與模糊查詢功能,涉及AngularJS過濾器、排序及字符串遍歷、查詢等相關(guān)操作技巧,需要的朋友可以參考下
    2017-12-12
  • AngularJS使用ng-app自動加載bootstrap框架問題分析

    AngularJS使用ng-app自動加載bootstrap框架問題分析

    這篇文章主要介紹了AngularJS使用ng-app自動加載bootstrap框架問題,分析了前面文章中所述的ng-app自動加載bootstrap出現(xiàn)的錯誤原因與相應(yīng)的解決方法,需要的朋友可以參考下
    2017-01-01
  • Angular使用Restful的增刪改

    Angular使用Restful的增刪改

    今天小編就為大家分享一篇關(guān)于Angular使用Restful的增刪改,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • 詳解Angular-Cli中引用第三方庫

    詳解Angular-Cli中引用第三方庫

    本篇文章主要介紹了詳解Angular-Cli中引用第三方庫 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • 詳解angular 中的自定義指令之詳解API

    詳解angular 中的自定義指令之詳解API

    本篇文章主要介紹了angular 中的自定義指令之詳解API,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • Angular中$cacheFactory的作用和用法實例詳解

    Angular中$cacheFactory的作用和用法實例詳解

    $cacheFactory是一個為Angular服務(wù)生產(chǎn)緩存對象的服務(wù)。接下來通過本文給大家介紹Angular中$cacheFactory的作用和用法實例詳解,非常不錯,感興趣的朋友一起看下吧
    2016-08-08

最新評論