Angular 路由错误 - this.router.navigateByUrl() 和 this.router.navigate()

Angular routing bug - this.router.navigateByUrl() and this.router.navigate()

我正在创建 angular 应用程序,它将以比自述文件更复杂的方式处理我的 GitHub 应用程序的文档。我想在点击 topnav 下拉菜单到选定的路线后重定向用户,但路由器有问题。 (我需要使用一些参数进行重定向,但即使使用简单的路径重定向也不起作用)。这些方法重定向到目标路由大约 1 秒(如例外),然后用户被重定向回根页面。

代码:

  /* First element is project name, second is category/part of application name */
  choices = ["typing_speed_test", "overview"]
  json = json

  constructor(private router: Router){}

  onProjectClick($event){
    this.choices[0] = $event.target.innerHTML.trim();
    this.choices[1] = "overview";
    this.redirect();
  }

  onCategoryClick($event){
    this.choices[1] = $event.target.innerHTML.trim();
    this.redirect();
  }

  redirect(){
    this.router.navigateByUrl("404");
  }

路线:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'project/:project_name/:category', component: SubpageComponent },
    { path: '404', component: NotFoundComponent },
    //{ path: '**', redirectTo: '404', pathMatch: 'full' }
];

Link 有问题的 gif:https://imgur.com/a/x2mPxvh github 存储库中的完整代码:https://github.com/Dolidodzik/DocsForMyApps(如果您使用此处的代码来回答这个问题,请在您的回答中指出)

我想我可能犯了一些愚蠢的错误,因为我是 Angular 的新手,但我做不到,因为每个 google 问题都显示我解决了错误,当重定向根本不起作用,不是像我这样的错误。

问题是你的 lins 看起来像这样:

 <a href="#" (click)="navigateInsideApp(routeX)">link</a>

默认 link 行为会导致您的应用从头开始重新加载。你应该使用 [routerLink]="['someUrl']" 而不是 href。如果您在某些情况下需要那个 href,请考虑调用 $event.preventDefault() 取消本机浏览器导航

您需要从导航栏的锚链接中删除 href="#"。它导致浏览器重新加载:

<a class="dropdown-item" *ngFor="let item of categories() | keyvalue">
  {{item.key}}
</a>

这也是一个有点奇怪的解决方案:

this.choices[0] = $event.target.innerHTML.trim();

您最好在模板中的函数调用中发送 item 变量,然后您可以在组件事件处理程序中读取它:

onProjectClick(item){
  this.choices[0] = item.key;
  this.choices[1] = "overview";
  this.redirect();
}