当前位置: 首页> 科技> 能源 > 重庆安全员c证查询官网_网络运营推广平台_重庆seo小z博客_搜索引擎营销的基本流程

重庆安全员c证查询官网_网络运营推广平台_重庆seo小z博客_搜索引擎营销的基本流程

时间:2025/9/6 9:24:04来源:https://blog.csdn.net/qq5678574/article/details/143287018 浏览次数:0次
重庆安全员c证查询官网_网络运营推广平台_重庆seo小z博客_搜索引擎营销的基本流程
  1. 创建 AuthGuard

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

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); // 或者使用 sessionStoragethis.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']); // 默认跳转到首页}}
}
  1. 在路由模块中配置守卫

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


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)。
用户成功登录后,登录组件会检查是否存在重定向路径,存在则跳转,否则进入默认首页。

关键字:重庆安全员c证查询官网_网络运营推广平台_重庆seo小z博客_搜索引擎营销的基本流程

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: