Angular 5按日期排序 [英] Angular 5 sort by date

查看:578
本文介绍了Angular 5按日期排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程表,我想按日期排序.由于Angular 5没有orderBy管道,到目前为止,我发现的所有解决方案都只能应用于数字和字符串,如果有人可以帮助我,我将不胜感激.这是我桌子的主体

I have a table of lessons and I would like to order them by date. Since Angular 5 doesn't have the orderBy pipe and all the solutions I have found so far can only be applied to numbers and strings I would be grateful if someone could help me with this. This is the body of my 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文件的一部分

and this is a fragment of my component.ts file

public lessons = [];

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

推荐答案

使用lessons进行排序订阅/绑定lessons之前,请在组件类中使用/Array/sort"rel =" nofollow noreferrer> Array.prototype.sort().这是在使用RxJS运算符map()进行降序绑定之前,对从服务中传入的lessons进行排序的方法.在转换subscribe()之前的数据流方面,map()确实非常强大.

Sort lessons using Array.prototype.sort() in your component class prior to subscribing/binding lessons. Here is how you can sort lessons coming in from your service prior to binding using RxJS operator map() in descending order. map() is really powerful in terms of transforming data streams prior to 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()来安抚编译器:

Depending on your TsLint settings/configuration, you may need to utilize getTime() to appease the compiler:

lessons.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())

这是 StackBlitz ,它显示了运行中的基本功能.

Here is a StackBlitz showing the basic functionality in action.

注意* -pipe() RxJS 5.5 + 一起使用.如果您使用的是RxJS的旧版本,则只需直接导入map()并按以下方式使用它即可:

Note* - pipe() is using with RxJS 5.5+. If you are using an older version of RxJS, you can simply just import map() directly and using it as follows:

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按日期排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆