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

Angular路由:如何用路径参数跳转并获取参数(隐藏?id=形式)

Angular路由路径参数配置与获取解决方案

1. 调整路由配置

修改product-routing.module.ts中的路由路径,匹配你需要的/record/:id格式:

const routes: Routes = [
  ...
  {
    path: 'electronic/billing/record/:id', // 调整路径,加入record和路径参数:id
    component: BillingSingleRecordComponent,
  },
  ...
];

@NgModule({
  imports: [RouterModule.forChild(routes), HttpClientModule],
  exports: [RouterModule],
})
export class ProductsRoutingModule {}

2. 修改父组件跳转逻辑

在product.component.ts的loadSingleRecord方法中,把ID作为路径的一部分传入,不再使用queryParams:

// 点击对应铅笔/编辑图标时调用的方法
loadSingleRecord() {
  const targetId = 12; // 实际场景替换为业务中的真实ID
  this._router.navigate(['products/electronic/billing/record', targetId]);
}

跳转后生成的URL会是localhost:4205/products/electronic/billing/record/12,符合你的格式需求。

3. 详情组件获取路径参数

在详情组件中,需要订阅路由的paramMap(官方推荐)或params来获取路径参数,而非queryParams(仅用于获取URL中?后的查询参数):

import { ActivatedRoute } from '@angular/router';

// 组件类构造函数注入ActivatedRoute
constructor(private activatedRoute: ActivatedRoute) {}

ngOnInit(): void {
  // 方式1:使用paramMap(Angular官方推荐)
  this.activatedRoute.paramMap.subscribe((paramMap) => {
    const id = paramMap.get('id');
    console.log(id); // 输出对应的ID值,比如29
    // 后续可根据ID发起详情数据请求
  });

  // 方式2:使用params(兼容旧版本,功能一致)
  // this.activatedRoute.params.subscribe((params) => {
  //   const id = params['id'];
  //   console.log(id);
  // });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:05:18