【发布时间】: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 还很陌生,但我也花了很多时间试图找出我做错了什么。与我从头到尾做的教程项目相比,一切都应该如此。
【问题讨论】: