Angular16的路由守卫基础使用

Angular16的路由守卫基础使用

  1. 使用ng generate guard /guard/login命令生成guard文件
  2. 因新版Angular取消了CanActivate的使用,改用CanActivateFn,因此使用router跳转需要通过inject的方式导入。
typescript 复制代码
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Router } from '@angular/router';

export const loginGuard: CanActivateFn = (route, state) => {
  const router = inject(Router);
  const token = localStorage.getItem('token');
  // 如果token有值,表示登录成功,继续跳转,否则跳转到首页
  if (token) {
    console.log("登陆成功");
    return true;
  }
  console.log("登陆失败");
  router.navigate(['/login']);
  return false;
};
  1. 在路由文件中,对需要守卫的路由地址配置guard
typescript 复制代码
const routes: Routes = [
  {
    path: 'demo',
    component: demoComponent,
    children: [
      {
        path: 'login',
        component: HeroesLoginComponent
      },
      {
        path: 'home',
        component: HomeComponent,
        canActivate: [loginGuard]
      }
      { path: '', redirectTo: 'home', pathMatch: 'full' }
    ]
  },
];
相关推荐
三十而立洋3 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁3 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄3 天前
JavaScript 隐式全局变量解析
javascript
沙蒿同学3 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端
paopaokaka_luck3 天前
智慧社区综合服务小程序(人脸识别、AI问答、Echarts图形化分析)
前端·javascript·spring boot·spring·数据分析·echarts
Hilaku3 天前
为什么死磕 1px 的团队,用户体验反而更差?
前端·javascript·程序员
陈拉斯3 天前
给公司年会写了个大屏抽奖系统:动画在前端跑,凭什么说结果没被改?
javascript
yzy853 天前
Vue中下载或打开文件的JavaScript方法
前端·javascript·vue
用户298698530143 天前
在 React 中用 JavaScript 将 Word 转换为文本
前端·javascript·react.js
李少兄3 天前
深入解析 JavaScript 中的 `document` 对象
javascript