路由守卫重定向页面

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

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

相关推荐
吴名氏.18 小时前
从零手写一个 AI Agent 框架(TypeScript 完整实现):Function Calling 循环、流式输出与错误恢复
人工智能·typescript·node.js·大模型·ai agent·functioncalling·llm 应用开发
濮水大叔1 天前
Cabloy/Zova 与 Next.js 的前端缓存差异
typescript·全栈·next.js
wflynn2 天前
GitHub 今日推荐|univer:可嵌入 Web 应用的开源 Office 引擎
typescript·开源·github·doc·collaboration·board
zhensherlock3 天前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
用户2972720767854 天前
从菜单树到运行时路由:途友后台权限管理系统设计复盘
typescript
Highcharts.js5 天前
Highcharts与TypeScript集成指南
前端·javascript·typescript·前端框架·数据可视化·highcharts
濮水大叔7 天前
Cabloy/Zova 与 Next.js 的 SSR 水合差异
前端·typescript·next.js
深兰科技7 天前
走出进博展馆寻AI方案,巴西政商联合体参访深兰科技洽商中巴产业数字化合作
人工智能·typescript·深兰科技·中巴产业数字化·巴西政商联合体·ai方案·进博会
FungLeo8 天前
成为全栈·Vue 管理后台篇·Biome、类型检查、构建和API 代理如何组成质量门禁
前端·javascript·vue.js·typescript·vite·前端工程化·biome
泯泷9 天前
改一个字,整段都红了?——中文内容差异对比的算法与协议设计
前端·javascript·typescript