首页 > 解决方案 > 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,
     );
   });     
 } 

标签: angularsortingdateangular5

解决方案


在订阅/绑定之前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);

推荐阅读