Angular 5 按日期排序

标签 angular sorting date angular5

我有一张类(class)表,我想按日期排序。由于 Angular 5 没有 orderBy 管道,并且到目前为止我发现的所有解决方案都只能应用于数字和字符串,如果有人可以帮助我,我将不胜感激。这是我 table 的主体

<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,
     );
   });     
 } 

最佳答案

使用Array.prototype.sort()类(class)进行排序在订阅/绑定(bind)类(class)之前在你的组件类中。以下是在绑定(bind)之前使用 RxJS 运算符 map() 以降序对来自服务的 lessons 进行排序的方法。 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);

关于Angular 5 按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334847/

相关文章:

ruby-on-rails - 如何在 Ruby 中对世界杯小组赛表进行排序

angular - Angular Material 中具有错误验证的ControlValueAccessor

javascript - 如何链接 Angular 2中的元素?

Angular2 指令、构造函数与 onInit

html - 使用组件函数设置 HTML 对象的样式

两个日期之间的 Javascript 天数返回错误

MySQL 按字母数字排序不起作用

Java - 排序类别

java - 多个日期条目之间的锻炼间隙

PHP 回显日期作为字符串