Angular:如何获取不含实际参数的原始路由路径
获取Angular路由的原始路径模板
要获取带参数占位符的路由原始路径(如pets/:petId/edit)而非实际参数值的URL,可通过遍历当前激活路由的配置信息来实现,具体步骤如下:
实现方法
- 在组件中注入
ActivatedRoute - 编写迭代函数,从当前路由向上追溯所有父路由,拼接各层级的路由配置路径
代码示例
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-pet-edit', templateUrl: './pet-edit.component.html', styleUrls: ['./pet-edit.component.css'] }) export class PetEditComponent implements OnInit { constructor(private route: ActivatedRoute) { } ngOnInit(): void { const routeTemplate = this.getRouteTemplate(); // 将获取到的路径模板传入分析工具即可 console.log(routeTemplate); // 输出: pets/:petId/edit } private getRouteTemplate(): string { let currentRoute: ActivatedRoute | null = this.route; const pathSegments: string[] = []; // 从当前路由向上遍历至根路由 while (currentRoute) { if (currentRoute.routeConfig?.path) { // 将当前路由的路径拆分为段,反向插入数组以保证路径顺序正确 const segments = currentRoute.routeConfig.path.split('/'); pathSegments.unshift(...segments); } currentRoute = currentRoute.parent; } return pathSegments.join('/'); } }
原理说明
ActivatedRoute的routeConfig.path属性存储了路由定义时的原始路径模板(包含:petId这类参数占位符)- 通过遍历当前路由的所有父路由,将各层级的路径片段按顺序拼接,即可得到完整的原始路由路径
- 该方法适配嵌套路由、懒加载路由等场景,能准确获取目标组件对应的路由模板
内容的提问来源于stack exchange,提问作者Jelle den Burger
相关产品推荐
相关产品推荐

