You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular登录后无法跳转至用户初始输入的访问URL如何解决

实现方案

1. 修改 auth.guard.ts 路由守卫逻辑

调整守卫方法获取用户要访问的目标地址,未登录时将目标地址作为参数携带到登录页:

// 顶部导入新增依赖
import { RouterStateSnapshot } from '@angular/router';

export class AuthGuard implements CanActivate {
  userProfile: any;
  constructor(private authService: AuthService, private route: Router,) {}
  // 新增 state 参数获取目标访问地址
  public async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
    const allowedUserRoles = this.getRoutePermissions(route);
    return await this.checkPermission(allowedUserRoles, state.url);
  }

  private getRoutePermissions(route: ActivatedRouteSnapshot): Roles[] {
    if (route.data && route.data.userRoles) {
      return route.data.userRoles as Roles[];
    }
    return null;
  }

  // 新增 targetUrl 入参接收目标地址
  private checkPermission(allowedUserRoles: Roles[], targetUrl: string): Promise<boolean> {
    return this.authService.getSession().then((session: boolean) => {
      if (session) {
        if (!allowedUserRoles) {
          return true;   // 未配置角色限制的路由所有用户可访问
        } else {
          let userRoles = JSON.parse(localStorage.getItem("userRoles"));
          if (this.authService.areUserRolesAllowed(userRoles, allowedUserRoles)) {
            return true;
          } else {
            this.route.navigateByUrl('/transactions');
            return false;
          }
        }
      } else {
        // 未登录时跳转到登录页,携带目标地址作为 query 参数
        this.route.navigate(['/login'], {
          queryParams: {
            redirectUrl: targetUrl
          }
        });
        return false;
      }
    });
  }
}

2. 修改登录组件逻辑

在登录成功的回调中,优先读取跳转参数跳回用户最初访问的地址,无跳转参数时跳转到默认页面:

// login.component.ts 代码示例
import { ActivatedRoute } from '@angular/router';

constructor(
  private authService: AuthService,
  private router: Router,
  private route: ActivatedRoute
) {}

// 你的登录成功处理方法
onLoginSuccess() {
  // 读取跳转参数
  const redirectUrl = this.route.snapshot.queryParamMap.get('redirectUrl');
  // 安全校验:只允许站内相对地址跳转,避免跳转到外部恶意站点
  const safeRedirect = redirectUrl?.startsWith('/') ? redirectUrl : '/transactions';
  this.router.navigateByUrl(safeRedirect);
}

内容的提问来源于stack exchange,提问作者user17418363

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:15:04