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 小时前
前端2秒生成500页矢量PDF,rust真的强到没朋友
前端·javascript·rust
梦想平凡4 小时前
百游棋牌源代码开发搭建教程(十):隔离部署、备份恢复与双端验收
java·前端·javascript·数据库·源代码管理
kyriewen8 小时前
我花3天抓了一个幽灵bug,凶手藏在第4层
前端·javascript·程序员
mONESY9 小时前
LangGraph.js 从零上手:把 Agent 工作流从一条线变成一张网
javascript
默_笙9 小时前
⚓ AI 的"官方答题卡":withStructuredOutput 与结构化输出的终局之战
前端·javascript
我家猫叫佩奇11 小时前
🦭 厌倦了千篇一律的线性图标?Naive Icons 正式开源
前端·javascript·css
晚安日记wanna12 小时前
TS const 类型参数一道面试题的四层追问
前端·面试·typescript
掰头战士12 小时前
你说你折这玩意干什么-agent工作的核心,还真得好好考虑怎么折叠上下文
typescript·llm·agent
ynchyong12 小时前
VUE 中 不能将类型“R[]”分配给类型“UnwrapRefSimple<R>[]”
typescript·vue·ts·unwraprefsimple
掰头战士13 小时前
让散乱的工具调用成为正规军,今天咱们聊聊 Tool System管线的读写锁
typescript·llm·agent