Angular 5 按日期排序

2024-02-04

我有一张课程表,我想按日期排序。由于 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,
     );
   });     
 } 

Sort lessons using Array.prototype.sort() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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())

这里有一个堆栈闪电战 https://stackblitz.com/edit/angular-xdbua9显示正在运行的基本功能。

Note* - 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular 5 按日期排序 的相关文章

随机推荐