路由守卫重定向页面

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

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

相关推荐
用户47949283569153 小时前
还不知道'use strict'的作用?这篇文章给你讲清楚
前端·javascript·typescript
乐影20 小时前
TS 模板字符串类型:从基础到进阶的类型编程魔法
前端·typescript
柯南二号21 小时前
【大前端】 TypeScript vs JavaScript:全面对比与实践指南
前端·javascript·typescript
濮水大叔1 天前
VonaJS AOP编程:全局中间件全攻略
typescript·nodejs·nestjs
歪歪1001 天前
ts-jest与其他TypeScript测试工具的对比
前端·javascript·测试工具·typescript·前端框架
mit6.8242 天前
理念导向编程|ts
rust·typescript
濮水大叔2 天前
AOP编程有三大场景:控制器切面,内部切面,外部切面,你get到了吗?
typescript·node.js·nestjs
朝与暮3 天前
史上最全typescript使用指南
typescript