对数据降序排序 Firebase Angular2 [英] Sort data descending list Firebase Angular2

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

问题描述

是否可以在 Angular2 中使用 Firebase 对值进行降序排序?在我的示例中,我想使用时间戳字段作为排序值.

Is it possible to sort values descending using Firebase in Angular2? In my example I want to use the timestamp field as the sort value.

我尝试过这种方法,但没有成功将其降序排序.

I have tried with this approach but haven't been succesfull in sorting it descending.

this.items = af.database.list('/items', {
      query: {
        orderByChild: 'timestamp'
      }
    });

我能想到的一种选择是在这些值到达时将它们推送到一个新数组,然后返回该数组,但这似乎不是最理想的.

One option I can think of would be pushing these values to a new array as they arrive and then return that array but that seems suboptimal.

推荐答案

我不熟悉 Firebase 查询,但是如果接收已经排序的数据不是一个严格的要求,您可以在接收数据后简单地对其进行排序.

I'm not familiar with Firebase queries, but if receiving the data already sorted isn't a strict requirement you could simply sort the data after receiving it.

//using ES 2016 syntax (copy and paste in latest Chrome dev tools to try out)

var times = [new Date('1/1/16').toISOString(),new Date('1/2/16').toISOString(),new Date('1/3/16').toISOString()];

console.log(times);
// ["2016-01-01T05:00:00.000Z", "2016-01-02T05:00:00.000Z", "2016-01-03T05:00:00.000Z"]

var sortedDesc = times.sort((t1,t2) => {
    if(t1 === t2) return 0;
    if(t1 > t2) return -1;
    if(t1 < t2) return 1;
});

console.log(sortedDesc);
// ["2016-01-03T05:00:00.000Z", "2016-01-02T05:00:00.000Z", "2016-01-01T05:00:00.000Z"]

这篇关于对数据降序排序 Firebase Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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