Firebase按日期说明使用Ionic Infinite滚动

时间:2018-05-02 16:51:55

标签: javascript firebase ionic-framework firebase-realtime-database ionic2

我想按日期desc(使用离子无限卷轴)订购评论列表,但它不起作用,排序不合适:

我尝试了什么:

  // How I push a new comment
  const ref=firebase.database().ref('/comment/'+imageId+'/').push();
  ref.set({
    created_at: firebase.database.ServerValue.TIMESTAMP
    ...
  })

enter image description here

按日期检索和排序:

ngOnInit():

  limit: number = 10;
  var items = [];
  this.listComments = db.ref('comment/'+this.imageId).orderByChild("created_at");

  this.listComments.limitToLast(this.limit).on('value', itemList => {
     itemList.forEach(function(data) {
        const user_id=data.val().user_id;
        db.ref('users/' + user_id).on('value',function(snap) {
             items.push({'displayName':snap.val().displayName,'created_at':data.val().created_at});
             return false;
         });
     });
  })
  this.commentArray=items;
 }

onInfiniteScroll(event):

let items = [];

this.limit += 2;
//same as before
this.listComments.limitToLast(this.limit).on('value', itemList => {
     itemList.forEach(function(data) {
        const user_id=data.val().user_id;
        db.ref('users/' + user_id).on('value',function(snap) {
             items.push({'displayName':snap.val().displayName,'created_at':data.val().created_at});
             return false;
         });
     });
  })

  setTimeout(() => {
     this.commentArray=items;
     event.complete();
   }, 500);

结果:

enter image description here

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

orderByChild按升序排序(docs)。您可以为created_at * -1的降序创建单独的密钥。这意味着旧的时间戳比新的时间戳更大。所以可能是这样的:

const ref = firebase.database().ref('comment').child(imageId).push();
ref.set({
  created_at: firebase.database.ServerValue.TIMESTAMP
})
.then(() => {
  return ref.child('created_at').once('value')
  .then((ss) => {
    return ref.child('created_at_desc').set(ss.val() * -1)
  })
})