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

查看:80
本文介绍了排序数据降序列表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天全站免登陆