Vasilis Michail
Vasilis Michail

Reputation: 403

Angular 4 Firebase angularfire Sorting a list by value

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?? ?

Upvotes: 1

Views: 3702

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600120

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,
    }
});

Upvotes: 1

Related Questions