Angular 5按日期排序

dob*_*obb 1 sorting date angular angular5

我有一个课程表,我想按日期排序。由于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>
Run Code Online (Sandbox Code Playgroud)

这是我的component.ts文件的片段

public lessons = [];

ngOnInit() {
this.localStorage.getItem<number>('selectedProfileId').subscribe((id) => {
     this._profileService.showLessons(id)
     .subscribe(data => this.lessons = data,
     );
   });     
 } 
Run Code Online (Sandbox Code Playgroud)

Ale*_*sky 6

订阅/绑定之前,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);
Run Code Online (Sandbox Code Playgroud)

根据您的TsLint设置/配置,您可能需要利用getTime()安抚编译器:

lessons.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
Run Code Online (Sandbox Code Playgroud)

这是一个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);
Run Code Online (Sandbox Code Playgroud)

希望有帮助!

谢谢!