angular - Angular 5 按日期排序
问题描述
我有一张课程表,我想按日期排序。由于 Angular 5 没有 orderBy 管道,并且到目前为止我发现的所有解决方案都只能应用于数字和字符串,如果有人可以帮助我,我将不胜感激。这是我桌子的主体
<tbody>
<tr *ngFor="let lesson of lessons">
<th scope="row">{{lesson.date | date:'dd.MM.yyyy H:mm'}}</th>
<td>{{lesson.address.locationName}}</td>
<td>{{lesson.topic}}</td>
<td>{{lesson.homework}}</td>
</tr>
</tbody>
这是我的 component.ts 文件的一个片段
public lessons = [];
ngOnInit() {
this.localStorage.getItem<number>('selectedProfileId').subscribe((id) => {
this._profileService.showLessons(id)
.subscribe(data => this.lessons = data,
);
});
}
解决方案
在订阅/绑定之前lessons
使用组件类中的Array.prototype.sort()进行排序lessons
。这是lessons
在使用 RxJS 运算符map()
以降序绑定之前从服务中传入的排序方式。map()
在转换之前的数据流方面确实非常强大subscribe()
。
this._profileService.showLessons(id)
.pipe(
map(lessons => lessons.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()))
)
.subscribe(lessons => this.lessons = lessons);
根据您的 TsLint 设置/配置,您可能需要使用getTime()
来安抚编译器:
lessons.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
这是一个StackBlitz,展示了基本功能。
注意* -pipe()
与RxJS 5.5+一起使用。如果您使用的是旧版本的 RxJS,您可以直接导入map()
并使用它,如下所示:
this._profileService.showLessons(id)
.map(lessons => lessons.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()))
.subscribe(lessons => this.lessons = lessons);
推荐阅读
- php - Looking for Laravel php developer to resolve updating function with image uploading its not working
- python - Tensorflow 确认权重已冻结
- ios - 打开 iOS 设置应用程序(顶级 - 不是应用程序设置页面的深层链接) - iOS 12/13
- ios - 如何在 Swift 中将键值对分解为 JSON 字符串?
- bash - 如何使用 git shortlog 在单个目录中的多个存储库中汇总用户提交统计信息?
- ruby-on-rails - How do you order a tournaments games by the name of each games field in Rails?
- javascript - 涉及异步功能时如何测量总时间
- opencl - 在 NVIDIA GPU 上编译 GPU 内核时出现预期表达式错误
- reactjs - How to save local storage cypress react
- c++ - 对 dlopen 的未定义引用