您好,欢迎访问一九零五行业门户网

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,会直接跳转到主页。
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
不同版本react路由跳转方法汇总
解析vue.js下载方式及使用步骤
以上就是angular路由守卫使用步骤详解的详细内容。
其它类似信息

推荐信息