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

Angular 15.1.2:如何在functional guard中获取RouterStateSnapshot?

在Angular函数式守卫中正确获取目标URL的方法

函数式守卫需通过守卫参数直接接收ActivatedRouteSnapshot和RouterStateSnapshot来获取目标URL,而非通过Router实例的snapshot——后者在守卫执行阶段还未更新到目标路由状态,因此返回空字符串。

修改你的函数式守卫代码,将route和state作为参数传入,直接使用state.url获取目标URL:

import { inject } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';

export const authGuard = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
  const router = inject(Router);
  const oAuthService = inject(OAuthService);
  const hasAccessToken = oAuthService.hasValidAccessToken();
  const hasIdToken = oAuthService.hasValidIdToken();

  console.log('targetUrl', state.url); // 正确获取目标URL

  if (!hasAccessToken || !hasIdToken) {
    router.navigate(['authenticate'], {
      state: {
        targetUrl: state.url,
      },
    });
  }
  return hasAccessToken;
};

原理说明

Angular路由守卫机制在执行守卫时,会将即将激活的路由快照(ActivatedRouteSnapshot)和路由状态快照(RouterStateSnapshot)作为参数传递给守卫函数。RouterStateSnapshot中的url属性就是用户试图访问的目标URL,这和类守卫中canActivate方法接收的state参数完全一致。而通过Router实例的routerState.snapshot获取的是当前已激活的路由状态,在守卫执行时还未切换到目标路由,因此返回空字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:20:59