最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

路由守衛(wèi)

守衛(wèi),顧名思義,必須滿足一定的條件得到許可方可通行,否則拒絕訪問(wèn)或者重定向。Angular中路由守衛(wèi)可以借此處理一些權(quán)限問(wè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(離開(kāi))。

一個(gè)所有守衛(wèi)都是通過(guò)的守衛(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)限控制邏輯如 是否登錄/擁有訪問(wè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)航將失敗/取消
  // 也可以寫(xiě)入具體的業(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í)寫(xiě)多個(gè)守衛(wèi),如果有也是分開(kāi)幾個(gè)文件(針對(duì)復(fù)雜場(chǎng)景,否則一般使用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 { }

使用場(chǎng)景分析

1.canLoad

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

2.canActivate

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

3.canActivateChild

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

4.CanDeactivate

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

場(chǎng)景模擬

登錄判斷

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

因?yàn)閘ogin是獨(dú)立一個(gè)頁(yè)面,所以app.component.html應(yīng)該只會(huì)剩余一個(gè)路由導(dǎo)航

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

取而代之的是pages.component.html頁(yè)面中要加入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í)寫(xiě)多個(gè)守衛(wèi),如果有也是分開(kāi)幾個(gè)文件(針對(duì)復(fù)雜場(chǎng)景,否則一般使用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: '公司主頁(yè)'
  }
 },
 {
  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寫(xiě)了頭部和底部組件卻沒(méi)顯示?

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

export class PagesComponent implements OnInit {

 constructor() { }

 ngOnInit() {
  alert();
 }

}

經(jīng)過(guò)刷新頁(yè)面,alert()窗口并沒(méi)有出現(xiàn)~,可想而知,直接通過(guò)路由模塊去加載了對(duì)應(yīng)組件;其實(shí)我們想要的效果就是之前改造前的app.component.html效果,所以路由配置要參照更改:

const routes: Routes = [
 {
  path: '',
  component: PagesComponent,
  children: [
   {
    path: '',
    redirectTo: 'index',
    pathMatch: 'full'
   },
   {
    path: 'index',
    component: IndexComponent,
    data: {
     title: '公司主頁(yè)'
    }
   },
   {
    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)
   },
  ]
 }
];

這樣寫(xiě),pages組件就被加載了,重回正題,差點(diǎn)回不來(lái),我們?cè)诘卿浗M件中寫(xiě)了簡(jiǎ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)限控制邏輯如 是否登錄/擁有訪問(wè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;
 }

路由離開(kāi)(選定應(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: '正在離開(kāi),是否需要保存改動(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)。

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

下一篇介紹路由事件的運(yùn)用。

總結(jié)

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

相關(guān)文章

最新評(píng)論

德州市| 宜城市| 左权县| 巫山县| 漳浦县| 井冈山市| 清水河县| 凤翔县| 沅江市| 漳浦县| 神农架林区| 绥棱县| 马关县| 清水河县| 开平市| 垣曲县| 新沂市| 潜江市| 囊谦县| 昔阳县| 高邑县| 牙克石市| 古丈县| 察雅县| 泽库县| 景宁| 九台市| 铜川市| 保山市| 沙河市| 云南省| 长武县| 乌拉特后旗| 博爱县| 灵丘县| 布尔津县| 灵寿县| 江陵县| 南陵县| 黔西县| 杭州市|