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' }
    ]
  },
];
相关推荐
竹林8181 小时前
用ethers.js连接MetaMask实现Web3钱包登录:从踩坑到稳定运行的完整记录
前端·javascript
心连欣1 小时前
从零开始,学习所有指令!
前端·javascript·vue.js
openKaka_3 小时前
从 scheduleUpdateOnFiber 到 Root 微任务调度:React 如何把更新交给调度系统
开发语言·前端·javascript
前进的李工3 小时前
智能Agent实战指南:记忆组件嵌入技巧(记忆)
开发语言·前端·javascript·python·langchain·agent
IOT.FIVE.NO.14 小时前
Codex Skill 内部结构解析:从 SKILL.md 到 scripts、references、assets
前端·javascript·人工智能·笔记·html
daols885 小时前
vue甘特图vxe-gantt如何实现拖拽任务条时如有已关联依赖线,同时更新依赖任务的日期的方式
javascript·vue.js·甘特图
我命由我123455 小时前
前端开发概念 - 无障碍树
javascript·css·笔记·学习·html·html5·js
ZC跨境爬虫6 小时前
跟着 MDN 学 HTML day_29:(动态构建与更新 DOM 树)
前端·javascript·ui·html·html5·媒体
搜狐技术产品小编20237 小时前
深度解析与业务实战:将 screenshot-to-code 改造为支持 React + Ant Design 的前端利器
前端·javascript·react.js·前端框架·ecmascript