Angular跳转到404页面时如何获取触发跳转的原始目标URL
Angular获取404触发前原始访问路径的方法
你当前配置的直接重定向逻辑会丢失路由跳转上下文,所以无法直接在404页面拿到原始路径,可通过以下两种方案实现:
方案一:修改路由配置传递原始路径(推荐,稳定性最高)
调整通配符路由规则,将原始访问路径作为参数传递到404页面,可按需选择两种实现方式:
方式1:通配符路由直接加载404模块(URL保留原始无效路径)
修改路由配置:
{ path: '404', loadChildren: () => import('../pages/404-pg/404-pg.module').then( (m) => m.FourZeroFourPgModule ), }, { path: '**', resolve: { // 注入Router获取当前导航的原始路径 originalUrl: () => inject(Router).getCurrentNavigation()?.initialUrl.toString() }, loadChildren: () => import('../pages/404-pg/404-pg.module').then( (m) => m.FourZeroFourPgModule ), }
在404组件中读取参数:
import { ActivatedRoute } from '@angular/router'; import { Component } from '@angular/core'; @Component({ // 你的404组件原有配置 }) export class FourZeroFourPgComponent { constructor(private route: ActivatedRoute) { const invalidUrl = this.route.snapshot.data['originalUrl']; // 此处可将invalidUrl上报到你的日志系统 console.log('用户访问的无效路径:', invalidUrl); } }
方式2:保留/404的URL显示,重定向时带查询参数
修改路由配置:
{ path: '404', loadChildren: () => import('../pages/404-pg/404-pg.module').then( (m) => m.FourZeroFourPgModule ), }, { path: '**', redirectTo: (route) => { // 拼接原始路径作为查询参数 const rawPath = route.url.map(seg => seg.path).join('/'); return `/404?originalUrl=${encodeURIComponent(rawPath)}`; } }
在404组件中读取参数:
import { ActivatedRoute } from '@angular/router'; import { Component } from '@angular/core'; @Component({ // 你的404组件原有配置 }) export class FourZeroFourPgComponent { constructor(private route: ActivatedRoute) { const rawUrl = this.route.snapshot.queryParams['originalUrl']; const invalidUrl = rawUrl ? decodeURIComponent(rawUrl) : ''; console.log('用户访问的无效路径:', invalidUrl); } }
方案二:不修改路由配置,直接读取导航状态
如果不想调整现有路由规则,可以直接在404组件的初始化同步阶段读取Router的导航记录:
import { Router } from '@angular/router'; import { Component } from '@angular/core'; @Component({ // 你的404组件原有配置 }) export class FourZeroFourPgComponent { constructor(private router: Router) { // 必须在组件初始化的同步阶段调用,异步回调中调用会返回null const currentNav = this.router.getCurrentNavigation(); const invalidUrl = currentNav?.initialUrl.toString() || this.router.url; console.log('用户访问的无效路径:', invalidUrl); } }
注意:该方案依赖Angular导航生命周期,仅当404组件初始化时导航尚未结束才能拿到正确值,极端场景下可能出现数据丢失,生产环境优先使用方案一。
内容的提问来源于stack exchange,提问作者Brandon Dixon
相关产品推荐
相关产品推荐

