【问题标题】:Angular doesn't remove colon (:) before routeAngular 不会在路由前删除冒号 (:)
【发布时间】:2017-11-11 22:13:13
【问题描述】:

在我自己的版本中,我一直在关注官方的 Angular 4 Hero 教程,我在其中显示学生列表,单击学生应该会显示详细信息。 我已经到了需要为每个组件执行路由的地步,并且遇到了我无法解决的问题,在设置路由之前它工作得很好。

基本上,问题在于 StudentDetailsComponent 的应用程序路由不起作用。我将它与教程进行了比较,发现在我的 URL 中,冒号 (:) 没有在学生索引之前被删除。

示例:localhost:4200/details/:140021 而在教程中将其删除,例如 localhost:4200/details/23

我很确定其余的代码是正确的,但我似乎找不到这条路线不起作用的原因。

这是我的 app-routing.module.ts:

const routes: Routes = [
  { path: '', redirectTo: '/list', pathMatch: 'full' },
  { path: 'list', component: AppComponent },
  { path: 'details/:index', component: StudentDetailsComponent },
];

这就是我在 student-details.component.ts 中获取索引的方式:

getStudent(): void {
   const index = +this.route.snapshot.paramMap.get('index');
   this.studentManagementService.getStudent(index).subscribe(student => 
   this.student = student);
}

这就是我在 student-management.service.ts 中获得实际选定学生的方式:

getStudent(index: number): Observable<Student>{
  return of(STUDENTS.find(student => student.index === index));
}

这就是我显示学生列表的方式,您应该可以从中单击学生并获取详细信息:

<li class="list-group-item" *ngFor="let student of students">
      <a routerLink="/details/:{{student.index}}">
        {{student.firstName}} {{student.lastName}}
      </a>
</li>

完整的代码可以在GitHub, branch: routing 上找到。

我真的不知道在哪里寻找错误,因为我对 Angular 还很陌生,但我也花了很多时间试图找出我做错了什么。与我从头到尾做的教程项目相比,一切都应该如此。

【问题讨论】:

标签: angular routing routes


【解决方案1】:

问题出在你的 routerLink 中。

改成:

<a [routerLink]="['/details', student.index]">

【讨论】:

  • 谢谢,这确实有效,尽管现在它只在我第一次点击学生时有效,之后即使 URL 根据所​​选索引发生相应变化,它也不会改变。我不知道为什么 Angular Heroes 教程中使用的示例在我的情况下不起作用,因为它基本上是一样的。
猜你喜欢
  • 1970-01-01
  • 2012-08-31
  • 2022-11-01
  • 1970-01-01
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 2021-07-22
相关资源
最近更新 更多