angularfire2按子值排序列表

时间:2018-05-24 04:20:51

标签: angular sorting firebase firebase-realtime-database angularfire

我有这样的firebase db

"students" : {
    "-LDD0MIigieZQ3Fcaj1Z" : {
      "ContactNo" : "0752155466",
      "Email" : "sdsdsd@sdsd.com",
      "FirstName" : "Ishana",
      "Gender" : "Female",
      "LastName" : "Dahanayake",
      "Password" : "1234",
      "score" : 6
    },
    "-LDD0ceFiy2RI1avfMWA" : {
      "ContactNo" : "0752155466",
      "Email" : "232323@sdsd.com",
      "FirstName" : "Ruwan",
      "Gender" : "Male",
      "LastName" : "Perera",
      "Password" : "1234",
      "score" : 1
    }
  }

我需要按得分

对这些学生进行排序

我试过这个

let ref = this.afDB.list('/students',ref=>ref.orderByChild('score')).snapshotChanges()
    .map(changes =>{
      return changes.map(c=> ({key:c.payload.key,...c.payload.val()}));
    });

    return ref;

但它没有根据得分值改变顺序。我如何对这些值进行排序?

2 个答案:

答案 0 :(得分:1)

如果你写了这段代码:

let ref = this.afDB.list('/students',ref=>ref.orderByChild('score')).snapshotChanges()
    .map(changes =>{
      return changes.map(c=> ({key:c.payload.key,...c.payload.val()}));
    });

    return ref;

返回你需要排序的值,我只想添加return ref.sort();

答案 1 :(得分:0)

你能这样试试吗

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, 
AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class ItemService {
  itemsCollection: AngularFirestoreCollection<any>;
  items: Observable<any>;
  itemDoc: AngularFirestoreDocument<any>;

  constructor(public afs: AngularFirestore) { 

    this.itemsCollection = this.afs.collection('students', ref => ref.orderBy('score','asc'));

    this.items = this.itemsCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        const data = a.payload.doc.data();
        data.id = a.payload.doc.id;
        return data;
      });
    });
  }