Search code examples
angularsortingfirebasefirebase-realtime-databaseangularfire

angularfire2 sort list by child value


I have my firebase db like this

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

I need to sort these students by score

i tried like this

    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;

but its not changing the order according to the score value.How can i sort these values?


Solution

  • If this code you wrote :

        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;
    

    returns you values you need to sort, i would just add return ref.sort();