路由守卫重定向页面

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

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

相关推荐
晚安日记wanna13 小时前
TS const 类型参数一道面试题的四层追问
前端·面试·typescript
掰头战士13 小时前
你说你折这玩意干什么-agent工作的核心,还真得好好考虑怎么折叠上下文
typescript·llm·agent
ynchyong13 小时前
VUE 中 不能将类型“R[]”分配给类型“UnwrapRefSimple<R>[]”
typescript·vue·ts·unwraprefsimple
掰头战士15 小时前
让散乱的工具调用成为正规军,今天咱们聊聊 Tool System管线的读写锁
typescript·llm·agent
半糖程序员19 小时前
从零构建 Agent(5):让事件流同时提供过程和结果
typescript·agent
西瓜太郎12341 天前
外层模型卡片与分组详情成功率不一致,应该怎么排查?
前端·typescript·go·软件工程·react
掰头战士1 天前
MCP、Skill、Plugin,都是给agent拓展能力,到底有何区别?
typescript·llm·agent
掰头战士2 天前
聊聊 Function Calling,你的模型是否答非所问?
前端·typescript·agent