當用戶知足必定條件才被容許進入或者離開一個路由。css
路由守衛場景:html
只有當用戶登陸並擁有某些權限的時候才能進入某些路由。數組
一個由多個表單組成的嚮導,例如註冊流程,用戶只有在當前路由的組件中填寫了知足要求的信息才能夠導航到下一個路由。服務器
當用戶未執行保存操做而試圖離開當前導航時提醒用戶。app
Angular提供了一些鉤子幫助控制進入或離開路由。這些鉤子就是路由守衛,能夠經過這些鉤子實現上面場景。dom
配置路由時候用到一些屬性,path, component, outlet, children, 路由守衛也是路由屬性。ide
實例:只讓登陸用戶進入產品信息路由。學習
新建guard目錄。目錄下新建login.guard.ts。this
LoginGuard類實現CanActivate接口,返回true或false,Angular根據返回值判斷請求經過或不經過。 spa
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 } ];
效果:點商品詳情連接控制檯會提醒用戶未登陸,不能進入商品詳情路由。
離開時候的路由守衛。提醒用戶執行保存操做後才能離開。
在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留在當前頁面。
http請求數據返回有延遲,致使模版沒法馬上顯示。
數據返回以前模版上全部須要用插值表達式顯示某個controller的值的地方都是空的。用戶體驗很差。
resolve解決辦法:在進入路由以前去服務器讀數據,把須要的數據都讀好之後,帶着這些數據進到路由裏,馬上就把數據顯示出來。
實例:
在進入商品信息路由以前,準備好商品信息再進入路由。 拿不到信息,或者拿信息出問題了,直接跳到錯誤信息頁面,或者彈出提示,就再也不進入目標路由。
先在product.component.ts中聲明商品信息類型。
export class Product{ constructor(public id:number, public name:string){ } }
在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){ } }
<div class="product"> <p> 這裏是商品信息組件 </p> <p> 商品id是: {{productId}} </p> <p> 商品名稱是: {{productName}} </p> <a [routerLink]="['./']">商品描述</a> <a [routerLink]="['./seller',99]">銷售員信息</a> <router-outlet></router-outlet> </div>
效果:
點商品詳情連接,傳入商品ID爲2,在resolve守衛中是正確id,會返回一條商品數據。
點商品詳情按鈕,傳入商品ID是3,是錯誤id,會直接跳轉到主頁。
本文做者starof,因知識自己在變化,做者也在不斷學習成長,文章內容也不定時更新,爲避免誤導讀者,方便追根溯源,請諸位轉載註明出處:http://www.cnblogs.com/starof/p/9012193.html 有問題歡迎與我討論,共同進步。