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' }
    ]
  },
];
相关推荐
Cobyte42 分钟前
21.Vue Vapor 组件的实现原理
前端·javascript·vue.js
铁皮饭盒1 小时前
Rust版Bun1.4之前, 盘点Bun1.3新特性
前端·javascript·后端
晓得迷路了1 小时前
栗子前端技术周刊第 135 期 - Vite 8.1、Rspack 2.1、Babel 8.0...
前端·javascript·vite
To_OC10 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC10 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
天渺工作室11 小时前
实现一个adblock/adblock plus等浏览器广告拦截器检测插件
前端·javascript
kyriewen18 小时前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
minglie1 天前
一个置换问题
javascript
默_笙1 天前
🌀 别再手动写 Prompt 了!我让 AI 自己循环改到满意为止
javascript
starrysky8101 天前
Ollama 部署五大崩溃:llama runner terminated exit 2、10分钟后停止服务、GGUF断言失败——逐一修复
angular.js