如何使用angular2按降序排序基于日期的数据

时间:2018-05-02 10:15:37

标签: angular typescript

我有一组数据显示。这里的日期没有按顺序排列。我希望数据根据日期按降序排列。

HTML:

<mat-tab label="Active">
  <mat-icon for="search">search</mat-icon>
  <input type="search" [(ngModel)]="filter" name="search" class="search" placeholder="Company">
  <ul>
    <li *ngFor="let message of activeMessages| messagefilter: filter" (click)="showMessage(message)" [class.activeShow]="message.id == message_id">
      <span>{{message.messages[message.messages.length -1].updated_at  | date:'dd.MM.yyyy'}}</span>
      <img style="width: 40px;" [src]="message.from_user_image || '../assets/images/msg.png'"/>
      <p style="padding-top: 16px;display: inline;">{{message.from_user_name}}</p>
      <p style="padding-top: 10px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"><b>{{message.messages[message.messages.length -1].text}}</b></p>
    </li>
  </ul>
</mat-tab>

TS:

loadMessages() {
    this.service
          .getMessages()
          .subscribe(
            data => {
              this.messagesdata = data;
              this.activeMessages = data.filter(msg => msg.active == true && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0)
              this.closedMessages = data.filter(msg => msg.active == false && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0);

            },error => {});
  }

enter image description here

这里我提取的日期来自数据中的messages数组。那么,任何人都可以帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

你可以这样做,

您可以对其中ViewModelthis.activeMessages updated date进行排序

您的TS将成为:

last message

您的HTML:

loadMessages() { 
    this.service 
    .getMessages() 
    .subscribe( 
    data => { 
        this.messagesdata = data; 
        this.activeMessages = data.filter(msg => msg.active == true && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0) 
        this.activeMessages = this.activeMessages.sort((a: any, b: any) => new Date(b.messages[b.messages.length -1].updated_at).getTime() - new Date(a.messages[a.messages.length -1].updated_at).getTime() 
        this.closedMessages = data.filter(msg => msg.active == false && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0); 
    },error => {}); 
}