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

Angular导航菜单右键点击功能求助:右键新标签页404错误

问题原因及修复步骤

1. 修复routerLink绑定错误

你的routerLink写法错误,将变量名当成了字面量路径,导致右键点击时浏览器请求了不存在的/gotolink?.path路径,引发404。

修改HTML中的routerLink:

<ng-container *ngFor="let gotolink of allLInks">
  <a
    class="nav"
    (click)="onClicktonav($event, gotolink?.path, gotolink.name)"
    [routerLink]="['/', gotolink?.path]"
    routerLinkActive="router-link-active"
  >
    <span class="Header-user-link-text">
      {{ gotolink.name }}
    </span>
  </a>
</ng-container>

说明:['/', gotolink?.path]会根据gotolink.path的值生成正确的根路由路径(比如gotolink.path为about时,生成/about)。如果你的gotolink.path本身已经包含前缀斜杠(比如/about),可以简化为[routerLink]="gotolink?.path"。

2. 修正TS中的参数错误并避免重复导航

你的TS代码里存在参数名错误(用了未定义的title),同时点击事件和routerLink会触发两次导航,需要优化:

onClicktonav(event: Event, path: string, name: string) {
  // 阻止routerLink的默认导航,避免重复跳转
  event.preventDefault();

  // 修复参数错误:将title改为name
  if (name === 'about') {
    this.gtmService.pushGTMTags('aboutpage', {
      fromPage: 'rightsidebar',
    });
  } else if (name === 'services') {
    // 补充services的GTM逻辑
  } else if (name === 'contact') {
    // 补充contact的GTM逻辑
  } else if (name === 'blog') {
    this.gtmService.pushGTMTags('blogpage');
  }

  // 手动触发导航
  this.router.navigate([path]);
}

说明:添加event.preventDefault()阻止routerLink的默认行为,避免和this.router.navigate重复导航;同时把所有title改为name,确保分支逻辑能正确执行。

如果不需要在导航前做额外逻辑(除了GTM),也可以去掉this.router.navigate,仅保留GTM统计,让routerLink处理导航:

TS代码修改:

onClicktonav(name: string) {
  if (name === 'about') {
    this.gtmService.pushGTMTags('aboutpage', {
      fromPage: 'rightsidebar',
    });
  } else if (name === 'services') {
    // 补充services的GTM逻辑
  } else if (name === 'contact') {
    // 补充contact的GTM逻辑
  } else if (name === 'blog') {
    this.gtmService.pushGTMTags('blogpage');
  }
}

HTML修改:

<ng-container *ngFor="let gotolink of allLInks">
  <a
    class="nav"
    (click)="onClicktonav(gotolink.name)"
    [routerLink]="['/', gotolink?.path]"
    routerLinkActive="router-link-active"
  >
    <span class="Header-user-link-text">
      {{ gotolink.name }}
    </span>
  </a>
</ng-container>

这种方式更符合Angular的路由最佳实践,同时右键点击新标签页会直接使用routerLink生成的正确href路径,不会出现404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:54:58