You need to enable JavaScript to run this app. Angular中ActivatedRoute无法获取URL的pdrId查询参数如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ActivatedRoute无法获取URL的pdrId查询参数如何解决

问题根因
  • route.snapshot.paramMap仅支持获取路由配置中定义的路径动态参数(例如URL/projects/46中的46,对应路由配置/projects/:projectId时可通过paramMap.get('projectId')获取),无法识别URL问号后的查询参数。你需要获取的pdrId属于查询参数,必须使用queryParamMap读取。
  • 此前获取的id恒为0的原因是paramMap.get('pdrId')返回null,Number(null)的转换结果为0,不满足if(id)的判断条件,因此不会给this.pdr.PDRId赋值。
修正后的代码
ngOnInit() {
  this.project = this.data.PdrProject;
  const id = Number(this.route.snapshot.queryParamMap.get('pdrId'));
  if (id) {
    this.pdr.PDRId = id;
  }
}
可选优化(参数校验)

如果需要避免参数缺失、非数字等异常场景,可增加参数合法性判断:

ngOnInit() {
  this.project = this.data.PdrProject;
  const rawPdrId = this.route.snapshot.queryParamMap.get('pdrId');
  const id = rawPdrId ? Number(rawPdrId) : 0;
  // 增加isNaN判断过滤无效数字
  if (id && !isNaN(id)) {
    this.pdr.PDRId = id;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:15:05