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

问题描述 投票:0回答:1

我正在创建一个角度应用程序,它将以比自述文件更复杂的方式处理我的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' }
];

链接到有问题的gif:https://imgur.com/a/x2mPxvhgithub repo中的完整代码:https://github.com/Dolidodzik/DocsForMyApps(如果您使用此处的代码来回答这个问题,请在答案中指出)

[我想我可能犯了一些愚蠢的错误,因为我在Angular中还很新,但是我却做不到,因为每个Google问题都显示了我可以解决ERRORS的问题,当重定向根本不起作用时,不像bug这样的错误以我的情况。

javascript angular routing
1个回答
0
投票

问题是您的林斯看起来像这样:

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

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


0
投票

您需要从导航栏中的锚链接中删除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();
}
© www.soinside.com 2019 - 2024. All rights reserved.