Angular路由重定向后如何获取并展示最初访问的无效路由地址
方案1:修改路由配置,直接将通配符路由绑定NotFound组件(推荐,改造量最小)
原配置中你是将**规则重定向到/not-found,可以省略重定向步骤,直接给通配符路由绑定NotFound组件:
const routes: Routes = [ { path: 'app', component: AppPage01Component }, { path: 'not-found', component: NotFoundComponent }, { path: 'root', redirectTo: 'app', pathMatch: 'full' }, { path: '', redirectTo: 'not-found', pathMatch: 'full' }, // 替换原来的重定向逻辑,直接绑定组件 { path: '**', component: NotFoundComponent } ];
之后在NotFoundComponent中注入ActivatedRoute即可直接获取原始无效路由:
import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) { } ngOnInit() { // 拼接得到完整原始路径 const invalidUrl = '/' + this.route.snapshot.url.map(segment => segment.path).join('/'); console.log(invalidUrl); // 输出示例:/XXX }
方案2:保留原有重定向逻辑,跳转时携带原始路径作为参数
如果业务要求必须保留重定向到/not-found的逻辑,可以使用Angular v14+支持的redirectTo函数语法,把原始路径作为查询参数传递:
首先修改路由配置:
const routes: Routes = [ { path: 'app', component: AppPage01Component }, { path: 'not-found', component: NotFoundComponent }, { path: 'root', redirectTo: 'app', pathMatch: 'full' }, { path: '', redirectTo: 'not-found', pathMatch: 'full' }, { path: '**', // 通过函数获取原始路径,拼接到重定向地址的查询参数中 redirectTo: (route) => { const invalidPath = route.url.map(segment => segment.path).join('/'); return `/not-found?invalidUrl=${encodeURIComponent(invalidPath)}`; }, pathMatch: 'full' } ];
之后在NotFoundComponent中读取查询参数即可:
import { ActivatedRoute } from '@angular/router'; constructor(private route: ActivatedRoute) { } ngOnInit() { const invalidUrl = decodeURIComponent(this.route.snapshot.queryParamMap.get('invalidUrl') || ''); console.log(invalidUrl); // 输出示例:XXX }
方案3:无需修改路由配置,直接从导航实例取原始地址
如果不想修改现有路由配置,也可以在NotFound组件中直接读取路由导航实例的初始地址:
import { Router } from '@angular/router'; constructor(private router: Router) { } ngOnInit() { // 只能在组件初始化同步阶段调用,异步逻辑调用会返回null const navigation = this.router.getCurrentNavigation(); const invalidUrl = navigation?.initialUrl.toString(); console.log(invalidUrl); // 输出示例:/XXX }
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

