路由守卫重定向页面

  1. 创建 AuthGuard

在 AuthGuard 中,检查用户的登录状态。如果未登录,则保存当前路径,然后导航到登录页面。

javascript 复制代码
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const isLoggedIn = /* 判断用户是否登录的逻辑 */;
    if (isLoggedIn) {
      return true;
    } else {
      // 如果未登录,保存目标路径,并跳转到登录页面
      localStorage.setItem('redirectUrl', state.url); // 或者使用 sessionStorage
      this.router.navigate(['/login']);
      return false;
    }
  }
}
  1. 登录页面登录逻辑
    在用户成功登录后,检查是否存在保存的目标路径,存在则跳转到目标路径,不存在则跳转到首页。
    下面展示一些 内联代码片

    import { Component } from '@angular/core';
    import { Router } from '@angular/router';

    @Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    })
    export class LoginComponent {
    constructor(private router: Router) {}

    onLoginSuccess() {
    // 执行登录逻辑,例如请求登录API

    复制代码
     // 登录成功后,检查并重定向到目标路径
     const redirectUrl = localStorage.getItem('redirectUrl');
     if (redirectUrl) {
       this.router.navigate([redirectUrl]);
       localStorage.removeItem('redirectUrl'); // 清除保存的路径
     } else {
       this.router.navigate(['/home']); // 默认跳转到首页
     }

    }
    }

  2. 在路由模块中配置守卫

在路由配置文件中添加 AuthGuard 到需要保护的路由。

javascript 复制代码
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent },
  // 其他路由配置
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

解释

当用户尝试访问受保护的页面但未登录时,AuthGuard 会将当前路径信息存储到 localStorage(或 sessionStorage)。

用户成功登录后,登录组件会检查是否存在重定向路径,存在则跳转,否则进入默认首页。

相关推荐
深海鱼在掘金15 小时前
深入浅出RAG——第7章:基础篇实战:文档问答机器人
人工智能·typescript·命令行
苏灿烤鱼18 小时前
Cursor 官方插件仓,许可证未声明
typescript·agent·cursor
濮水大叔18 小时前
CabloyJS 强大之处不仅仅是 IoC,而是全栈资源的寻址体系
typescript·node.js·全栈
To_OC1 天前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
mCell1 天前
用 Cordis 从零构建一个 Mini DeepSeek Harness
typescript·agent·deepseek
满栀5852 天前
状态管理:Redux、Vuex、Pinia 核心区别
前端·javascript·typescript
苏灿烤鱼2 天前
公司**不可计算,就自己做操作系统
rust·typescript·agent
sunly_2 天前
TypeScript总结:16、面向对象速查
前端·javascript·typescript
gs801402 天前
解构 Cordis:面向“时空可组合性”的 TypeScript 元框架深度剖析
前端·javascript·typescript
sunly_2 天前
TypeScript总结:15、类型速查
前端·javascript·typescript