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

Angular如何实现带URL参数的组件路由及ActivatedRoute参数获取

Angular带参路由跳转失效修复方案

  • 路由模块导入拼写错误
    app.module.ts中导入AppRoutingModule的文件名拼写错误,现有代码写为./app-rounting.module,正确应为./app-routing.module(routing拼写错误,多写了n、漏写了t),会导致路由规则不生效。

  • 缺少路由出口占位符
    app.component.html中没有添加<router-outlet>标签,路由匹配到的组件需要渲染在该标签位置,缺失时跳转后组件不会在页面显示。修改后的app.component.html代码如下:

    <hello name="{{ name }}"></hello>
    <p>Start editing to see some magic happen :)</p>
    <a (click)="routeToComponent()">Click to route</a>
    <!-- 新增路由出口 -->
    <router-outlet></router-outlet>
    
  • 路由跳转写法可优化(非强制错误)
    现有this.router.navigate(['/heros/23'])的写法可正常运行,更符合Angular规范的动态参数写法是将路径和参数拆分:

    this.router.navigate(['/heros', 23]);
    

    也可使用navigateByUrl方法直接传入完整路径:

    this.router.navigateByUrl('/heros/23');
    

修复以上问题后,点击跳转按钮即可正常渲染HerosComponent,控制台会同步打印获取到的URL参数{id: '23'}。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:24:08