Zekelonas Zekelonas - 26 days ago 10
TypeScript Question

Angular 4 Firebase Observable with .map() apears two times on refresh and not reversed

I am using Angular 4 with Firebase and AngularFire. I want to display on my Html code the first top 10 users, so my code is

export class HomefillerComponent implements OnInit {
topusers: Observable<any>;
constructor(db: AngularFireDatabase,public authService: AuthService) {

this.topusers = db.list('users', {
query: {
orderByChild: "totalscore",
limitToLast: 10,
}).map((topusers) => {console.log(topusers);
return topusers.reverse();})

My firebase database is:

"users" : {
"Test1" : {
"totalscore" : 50,
"username" : "test1"
"Test2" : {
"totalscore" : 30,
"username" : "test2"
"Test3" : {
"totalscore" : 20,
"username" : "test1"
"Test4" : {
"totalscore" : 10,
"username" : "test1"
"Zekes" : {
"totalscore" : 14,
"username" : "Zekes"

When I navigate in my angular 4 app everything works fine.However when I refrest the page I get two
one with the reversed object and a second one with not the reversed object.So my html displays the not reversed object.
Do you have any idea of what is wrong?? It only happens when I refresh the page.
This is the
I get when I refresh the page.This is the <code>console.log(a)</code> I get when I refresh the page.

Answer Source

After some testing I discovered what's happening:

The thing is that the .reverse() function not only returns a reversed array, but reverses the array itself. And this change to topusers result in the Observable firing .map() once again, which reverses the array back to its original form.

To solve this problem simply change the return statement to return topusers.slice().reverse();. The .slice() function returns a new copy of the array, which will prevent this problem.