Sort data descending list Firebase Angular2

懵懂的女人 提交于 2019-12-11 04:44:08

问题


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.


回答1:


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"]


来源:https://stackoverflow.com/questions/41185647/sort-data-descending-list-firebase-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!