路由守卫重定向页面

  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)。

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

相关推荐
流影ng1 天前
【HarmonyOS】并发线程间的通信
typescript·harmonyos
duansamve1 天前
TS在Vue3中的使用实例集合
typescript·vue3
FanetheDivine2 天前
ts中如何描述一个复杂函数的类型
前端·typescript
struggle20253 天前
AxonHub 开源程序是一个现代 AI 网关系统,提供统一的 OpenAI、Anthropic 和 AI SDK 兼容 API
css·人工智能·typescript·go·shell·powershell
执剑、天涯3 天前
通过一个typescript的小游戏,使用单元测试实战(二)
javascript·typescript·单元测试
chéng ௹3 天前
Vue3+Ts+Element Plus 权限菜单控制节点
前端·javascript·vue.js·typescript
武清伯MVP4 天前
阮一峰《TypeScript 教程》学习笔记——基本用法
笔记·学习·typescript
ttod_qzstudio5 天前
解决 Vue 3 + TypeScript 中 v-for 循环类型推断问题
前端·vue.js·typescript
今天头发还在吗6 天前
【React】动态SVG连接线实现:图片与按钮的可视化映射
前端·javascript·react.js·typescript·前端框架
冷冷的菜哥6 天前
react多文件分片上传——支持拖拽与进度展示
前端·react.js·typescript·多文件上传·分片上传