1

I am using Angular 4 Firebase and AngularFire and i have the following firebase database

"users" : {
    "Test1" : {
      "totalscore" : 50,
      "username" : "test1"
    },
    "Test2" : {
      "totalscore" : 30,
      "username" : "test2"
    },
    "Test3" : {
      "totalscore" : 20,
      "username" : "test1"
    },
    "Test4" : {
      "totalscore" : 10,
      "username" : "test1"
    },
    "Test5" : {
      "totalscore" : 50,
      "username" : "test1"
    },
    "Test6" : {
      "totalscore" : 30,
      "username" : "test2"
    },
    "Test7" : {
      "totalscore" : 20,
      "username" : "test1"
    },
    "Test8" : {
      "totalscore" : 10,
      "username" : "test1"
    }
  }

I read the documents of firebase and AngularFire and I want to get those data as a sorted list by totalscore.I tried all the possible ways given by this AngularFire link but nothing helped.I currently got this code which works fine but it doesnt sort the list.

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';

@Component({
  selector: 'app-homefiller',
  templateUrl: './homefiller.component.html',
  styleUrls: ['./homefiller.component.css']
})

export class HomefillerComponent implements OnInit {
  topusers: FirebaseListObservable<any>;
  totalscore;
  list;
  constructor(db: AngularFireDatabase) {


        this.topusers = db.list('users', {
        query: {
         orderByValue: true,
         limitToFirst: 10,
        }
        });
   }

  ngOnInit() {
  }

}

Can you help me with a way to sort my list by

"totalscore:"

or tell me if it is possible to do that?? ?

Vasilis Michail
  • 403
  • 2
  • 6
  • 17

1 Answers1

1

The orderByValue is used when you have a data structure like this:

"userscores" : {
    "Test1" : 50,
    "Test2" : 30,
    "Test3" : 20
    "Test4" : 10,
}

In the above you want to order the results of your query on userscores on the value of each child node.

In your case, the value you want to sort on is in a child property totalscore under users. So you should use orderByChild:

this.topusers = db.list('users', {
    query: {
     orderByChild: "totalscore",
     limitToFirst: 10,
    }
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Ah thank you very much this worked!! It gets the list from the smaller to the bigger and I prefer the opossite is there any way to invert it?? – Vasilis Michail Aug 05 '17 at 16:51
  • 1
    Firebase always returns the items in ascending order. Two options are to: 1) reverse the result client side, 2) store an inverted value for querying. See [this answer](https://stackoverflow.com/questions/41185647/sort-data-descending-list-firebase-angular2) and [this answer](https://stackoverflow.com/questions/25611356/display-posts-in-descending-posted-order/25613337#25613337) respectively. – Frank van Puffelen Aug 05 '17 at 16:59