您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

浅谈angular9中路由守卫的用法

2024/4/19 11:11:12发布18次查看
本篇文章给大家介绍一下angular路由守卫的使用。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
路由守卫是什么
任何用户都能在任何时候导航到任何地方。但有时候出于种种原因需要控制对该应用的不同部分的访问。可能包括如下场景:
该用户可能无权导航到目标组件。
可能用户得先登录(认证)。
在显示目标组件前,你可能得先获取某些数据。
在离开组件前,你可能要先保存修改。
你可能要询问用户:你是否要放弃本次更改,而不用保存它们?
相关推荐:《angular教程》
组件的创建
1、home组件创建
2、login组件创建
3、home下的first和second子组件
守卫路由相关核心代码
routing中每个路由都是对所有人开放的。这些新的管理特性应该只能被已登录用户访问。
编写一个 canactivate() 守卫,将正在尝试访问管理组件匿名用户重定向到登录页。
1.1 在auth 文件夹下,新建一个auth.service.ts文件,模拟有关登录的请求服务,实际场景一般是将后台token保存在cookie中.
import { injectable } from '@angular/core';import { observable, of } from 'rxjs';import { tap, delay } from 'rxjs/operators';@injectable({  providedin: 'root',})export class authservice {  isloggedin = false; //默认未登录  // 记录登录之后,需要跳转到原来请求的地址  redirecturl: string;// 登录  login(): observable<boolean> {    return of(true).pipe(      delay(1000),      tap(val => this.isloggedin = true)    );  }// 登出  logout(): void {    this.isloggedin = false;  }}
1.2 在 auth 文件夹下,新建一个auth.guard.ts文件
import { injectable } from '@angular/core';import { canactivate, activatedroutesnapshot, routerstatesnapshot, router } from '@angular/router';import { authservice } from './auth.service'; @injectable({  providedin: 'root',})export class authguard implements canactivate {  constructor(private authservice: authservice, private router: router) {}  canactivate(    next: activatedroutesnapshot,    state: routerstatesnapshot): boolean {    let url: string = state.url    return this.checklogin(url);  }    checklogin(url: string): boolean {    if (this.authservice.isloggedin) { return true; }    // 保存原始的请求地址,登录后跳转到该地址    this.authservice.redirecturl = url;    // 未登录,跳转到登录页面    this.router.navigate(['/login']);    return false;  }}
在路由中使用守卫
在app-routing.module.ts文件下使用
import { ngmodule } from '@angular/core';import { routes, routermodule } from '@angular/router';import { authguard } from './auth/auth.guard';import { logincomponent } from './login/login.component';const routes: routes = [  {    path: '',    redirectto: '/home',    pathmatch: 'full'  },   {    path: 'login',    component: logincomponent  },  {    path: 'home',    loadchildren: () => import('./home/home.module')      .then(mod => mod.homemodule),    canactivate: [authguard], // 守卫路由  }];@ngmodule({  imports: [routermodule.forroot(routes)],  exports: [routermodule]})export class approutingmodule {}
最后的结尾
一般路由守卫与拦截器一起使用,感兴趣可以了解一下.
更多编程相关知识,请访问:编程视频!!
以上就是浅谈angular9中路由守卫的用法的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product