Angular在路由之前不会删除冒号(:)

时间:2017-11-11 22:13:13

标签: angular routing routes

我在我自己的版本中一直关注官方的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很新,但我也花了很多时间试图找到我做错的事情。与我从头到尾所做的教程项目相比,一切都是应有的。

1 个答案:

答案 0 :(得分:0)

问题在于您的routerLink。

将其更改为:

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