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

1 Answer 1

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,
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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??
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 and this answer respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.