Angular路由守衛使用步驟詳解
這次帶給大家Angular路由守衛使用步驟詳解,Angular路由守衛使用的注意事項有哪些,下面就是實戰案例,一起來看一下。
一、路由守衛
當使用者滿足某個條件才被允許進入或離開一個路由。
路由守衛場景:
只有當使用者登入並且擁有某些權限的時候才能進入某些路由。
一個由多個表單組成的嚮導,例如註冊流程,使用者只有在目前路由的元件中填寫了滿足要求的資訊才可以導航到下一個路由。
當使用者未執行儲存操作而試圖離開目前導覽時提醒使用者。
Angular提供了一些鉤子幫助控制進入或離開路由。這些鉤子就是路由守衛,可以透過這些鉤子實現上面場景。
CanActivate: 處理導航到某路由的情況。
CanDeactivate: 處理從目前路由離開的情況。
Resolve: 在路由啟動前取得路由資料。
設定路由時候用到一些屬性,path, component, outlet, children, 路由守衛也是路由屬性。
二、CanActivate
實例:只讓登入使用者進入產品資訊路由。
新guard目錄。目錄下新建login.guard.ts。
LoginGuard類別實作CanActivate接口,傳回true或false,Angular根據回傳值判斷請求通過或不通過。
import { CanActivate } from "@angular/router"; export class LoginGuard implements CanActivate{ canActivate(){ let loggedIn :boolean= Math.random()<0.5; if(!loggedIn){ console.log("用户未登录"); } return loggedIn; } }
設定product路由。先把LoginGuard加入providers,在指定路由守衛。
canActivate可以指定多個守衛,值是一個陣列。
const routes: Routes = [ { path: '', redirectTo : 'home',pathMatch:'full' }, { path: 'chat', component: ChatComponent, outlet: "aux"},//辅助路由 { path: 'home', component: HomeComponent }, { path: 'product/:id', component: ProductComponent, children:[ { path: '', component : ProductDescComponent }, { path: 'seller/:id', component : SellerInfoComponent } ] ,canActivate: [LoginGuard]}, { path: '**', component: Code404Component } ];
效果:點商品詳情連結控制台會提醒使用者未登錄,無法進入商品詳情路由。
三、CanDeactivate
#離開時候的路由守衛。提醒使用者執行儲存操作後才能離開。
在guard目錄下新建一個unsave.guard.ts的檔案。
CanDeactivate介面有一個範式,指定目前元件的類型。
CanDeactivate方法第一個參數是介面指定的範式類型的元件,根據這個要保護的元件的狀態,或是呼叫方法來決定使用者是否能夠離開。
import { CanDeactivate } from "@angular/router"; import { ProductComponent } from "../product/product.component"; export class UnsaveGuard implements CanDeactivate<ProductComponent>{ //第一个参数 范型类型的组件 //根据当前要保护组件 的状态 判断当前用户是否能够离开 canDeactivate(component: ProductComponent){ return window.confirm('你还没有保存,确定要离开吗?'); } }
設定路由,同樣先加到provider,再設定路由。
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProductComponent } from './product/product.component'; import { Code404Component } from './code404/code404.component'; import { ProductDescComponent } from './product-desc/product-desc.component'; import { SellerInfoComponent } from './seller-info/seller-info.component'; import { ChatComponent } from './chat/chat.component'; import { LoginGuard } from './guard/login.guard'; import { UnsaveGuard } from './guard/unsave.guard'; const routes: Routes = [ { path: '', redirectTo : 'home',pathMatch:'full' }, { path: 'chat', component: ChatComponent, outlet: "aux"},//辅助路由 { path: 'home', component: HomeComponent }, { path: 'product/:id', component: ProductComponent, children:[ { path: '', component : ProductDescComponent }, { path: 'seller/:id', component : SellerInfoComponent } ] ,canActivate: [LoginGuard], canDeactivate: [UnsaveGuard]}, { path: '**', component: Code404Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [LoginGuard,UnsaveGuard] }) export class AppRoutingModule { }
效果:
點ok離開目前頁面,cancel留在目前頁面。
四、Resolve守衛
#http要求資料回傳有延遲,導致模版無法立刻顯示。
資料傳回之前模版上所有需要用插值表達式顯示某個controller的值的地方都是空的。用戶體驗不好。
resolve解決方法:在進入路由之前去伺服器讀數據,把需要的數據都讀好以後,帶著這些數據進到路由裡,立刻就把數據顯示出來。
實例:
在進入商品資訊路由之前,準備好商品資訊再進入路由。拿不到訊息,或是拿訊息出問題了,直接跳到錯誤訊息頁面,或是彈出提示,就不再進入目標路由。
先在product.component.ts中宣告商品資訊類型。
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProductComponent } from './product/product.component'; import { Code404Component } from './code404/code404.component'; import { ProductDescComponent } from './product-desc/product-desc.component'; import { SellerInfoComponent } from './seller-info/seller-info.component'; import { ChatComponent } from './chat/chat.component'; import { LoginGuard } from './guard/login.guard'; import { UnsaveGuard } from './guard/unsave.guard'; const routes: Routes = [ { path: '', redirectTo : 'home',pathMatch:'full' }, { path: 'chat', component: ChatComponent, outlet: "aux"},//辅助路由 { path: 'home', component: HomeComponent }, { path: 'product/:id', component: ProductComponent, children:[ { path: '', component : ProductDescComponent }, { path: 'seller/:id', component : SellerInfoComponent } ] ,canActivate: [LoginGuard], canDeactivate: [UnsaveGuard]}, { path: '**', component: Code404Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [LoginGuard,UnsaveGuard] }) export class AppRoutingModule { }
在guard目錄下新建product.resolve.ts。 ProductResolve類別實作了Resolve介面。
Resolve也要宣告一個範式,範型就是resolve要解析出來的資料的型別。
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router"; import { Injectable } from "@angular/core"; import { Observable } from "rxjs/Observable"; import { Product } from "../product/product.component"; @Injectable() export class ProductResolve implements Resolve<Product>{ constructor(private router: Router) { } resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any { let productId: number = route.params["id"]; if (productId == 2) { //正确id return new Product(1, "iPhone7"); } else { //id不是1导航回首页 this.router.navigate(["/home"]); return undefined; } } }
路由配置:Provider里声明,product路由里配置。
resolve是一个对象,对象里参数的名字就是想传入的参数的名字product,用ProductResolve来解析生成。
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { ProductComponent } from './product/product.component'; import { Code404Component } from './code404/code404.component'; import { ProductDescComponent } from './product-desc/product-desc.component'; import { SellerInfoComponent } from './seller-info/seller-info.component'; import { ChatComponent } from './chat/chat.component'; import { LoginGuard } from './guard/login.guard'; import { UnsaveGuard } from './guard/unsave.guard'; import { ProductResolve } from './guard/product.resolve'; const routes: Routes = [ { path: '', redirectTo : 'home',pathMatch:'full' }, { path: 'chat', component: ChatComponent, outlet: "aux"},//辅助路由 { path: 'home', component: HomeComponent }, { path: 'product/:id', component: ProductComponent, children:[ { path: '', component : ProductDescComponent }, { path: 'seller/:id', component : SellerInfoComponent } ] , // canActivate: [LoginGuard], // canDeactivate: [UnsaveGuard], resolve:{ //resolve是一个对象 product : ProductResolve //想传入product,product由ProductResolve生成 }}, { path: '**', component: Code404Component } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [LoginGuard,UnsaveGuard,ProductResolve] }) export class AppRoutingModule { }
修改一下product.component.ts 和模版,显示商品id和name。
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.css'] }) export class ProductComponent implements OnInit { private productId: number; private productName: string; constructor(private routeInfo: ActivatedRoute) { } ngOnInit() { // this.routeInfo.params.subscribe((params: Params)=> this.productId=params["id"]); this.routeInfo.data.subscribe( (data:{product:Product})=>{ this.productId=data.product.id; this.productName=data.product.name; } ); } } export class Product{ constructor(public id:number, public name:string){ } }
<p class="product"> <p> 这里是商品信息组件 </p> <p> 商品id是: {{productId}} </p> <p> 商品名称是: {{productName}} </p> <a [routerLink]="['./']">商品描述</a> <a [routerLink]="['./seller',99]">销售员信息</a> <router-outlet></router-outlet> </p>
效果:
点商品详情链接,传入商品ID为2,在resolve守卫中是正确id,会返回一条商品数据。
点商品详情按钮,传入商品ID是3,是错误id,会直接跳转到主页。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上是Angular路由守衛使用步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

iPhone上的預設地圖是Apple專有的地理位置供應商「地圖」。儘管地圖越來越好,但它在美國以外的地區運作不佳。與谷歌地圖相比,它沒有什麼可提供的。在本文中,我們討論了使用Google地圖成為iPhone上的預設地圖的可行性步驟。如何在iPhone中使Google地圖成為預設地圖將Google地圖設定為手機上的預設地圖應用程式比您想像的要容易。請依照以下步驟操作–先決條件步驟–您必須在手機上安裝Gmail。步驟1–開啟AppStore。步驟2–搜尋“Gmail”。步驟3–點選Gmail應用程式旁

不斷推出新版本以提供更好的使用體驗,微信作為中國的社交媒體平台之一。升級微信至最新版本是非常重要的,家人和同事的聯繫、為了保持與朋友、及時了解最新動態。 1.了解最新版本的特性與改進了解最新版本的特性與改進非常重要,在升級微信之前。效能改進和錯誤修復,透過查看微信官方網站或應用程式商店中的更新說明、你可以了解新版本所帶來的各種新功能。 2.檢查目前微信版本我們需要檢查目前手機上已安裝的微信版本、在升級微信之前。點擊,打開微信應用“我”然後選擇,菜單“關於”在這裡你可以看到當前微信的版本號,。 3.打開應

使用AppleID登入iTunesStore時,可能會在螢幕上拋出此錯誤提示「此AppleID尚未在iTunesStore中使用」。沒有什麼可擔心的錯誤提示,您可以按照這些解決方案集進行修復。修正1–更改送貨地址此提示出現在iTunesStore中的主要原因是您的AppleID個人資料中沒有正確的地址。步驟1–首先,開啟iPhone上的iPhone設定。步驟2–AppleID應位於所有其他設定的頂部。所以,打開它。步驟3–在那裡,打開“付款和運輸”選項。步驟4–使用面容ID驗證您的存取權限。步驟

CrystalDiskMark是一款適用於硬碟的小型HDD基準測試工具,可快速測量順序和隨機讀取/寫入速度。接下來就讓小編為大家介紹一下CrystalDiskMark,以及crystaldiskmark如何使用吧~一、CrystalDiskMark介紹CrystalDiskMark是一款廣泛使用的磁碟效能測試工具,用於評估機械硬碟和固態硬碟(SSD)的讀取和寫入速度和隨機I/O性能。它是一款免費的Windows應用程序,並提供用戶友好的介面和各種測試模式來評估硬碟效能的不同方面,並被廣泛用於硬體評

iPhone上的Shazam應用程式有問題? Shazam可協助您透過聆聽歌曲找到歌曲。但是,如果Shazam無法正常工作或無法識別歌曲,則必須手動對其進行故障排除。修復Shazam應用程式不會花費很長時間。因此,無需再浪費時間,請按照以下步驟解決Shazam應用程式的問題。修正1–禁用粗體文字功能iPhone上的粗體文字可能是Shazam無法正常運作的原因。步驟1–您只能從iPhone設定執行此操作。所以,打開它。步驟2–接下來,開啟其中的「顯示和亮度」設定。步驟3–如果您發現啟用了“粗體文本

foobar2000是一款能隨時收聽音樂資源的軟體,各種音樂無損音質帶給你,增強版本的音樂播放器,讓你得到更全更舒適的音樂體驗,它的設計理念是將電腦端的高級音頻播放器移植到手機上,提供更便捷高效的音樂播放體驗,介面設計簡潔明了易於使用它採用了極簡的設計風格,沒有過多的裝飾和繁瑣的操作能夠快速上手,同時還支持多種皮膚和主題,根據自己的喜好進行個性化設置,打造專屬的音樂播放器支援多種音訊格式的播放,它還支援音訊增益功能根據自己的聽力情況調整音量大小,避免過大的音量對聽力造成損害。接下來就讓小編為大

螢幕截圖功能在您的iPhone上不起作用嗎?截圖非常簡單,因為您只需同時按住「提高音量」按鈕和「電源」按鈕即可抓取手機螢幕。但是,還有其他方法可以在設備上捕獲幀。修復1–使用輔助觸控使用輔助觸控功能截取螢幕截圖。步驟1–轉到您的手機設定。步驟2–接下來,點選以開啟「輔助功能」設定。步驟3–開啟「觸摸」設定。步驟4–接下來,開啟「輔助觸控」設定。步驟5–打開手機上的「輔助觸控」。步驟6–打開“自訂頂級選單”以存取它。步驟7–現在,您只需將這些功能中的任何一個連結到螢幕擷取即可。因此,點擊那裡的首

您的手機中缺少時鐘應用程式嗎?日期和時間仍將顯示在iPhone的狀態列上。但是,如果沒有時鐘應用程序,您將無法使用世界時鐘、碼錶、鬧鐘等多項功能。因此,修復時鐘應用程式的缺失應該是您的待辦事項清單的首位。這些解決方案可以幫助您解決此問題。修復1–放置時鐘應用程式如果您錯誤地從主畫面中刪除了時鐘應用程序,您可以將時鐘應用程式放回原位。步驟1–解鎖iPhone並開始向左側滑動,直到到達「應用程式庫」頁面。步驟2–接下來,在搜尋框中搜尋「時鐘」。步驟3–當您在搜尋結果中看到下方的「時鐘」時,請按住它並
