0

I'm using firebase and Angular, here is my database with my users :

Picture of my database

I want to sort my user by "ptsTotal".

I have a users.service with a function getUsersByPoints. But when I'm using it the console return to me : this.users.sort is not a function.

I don't see where I'm doing a mistake. could you help me to find the mistake or give me another solution to sort my user ?

Thanks a lot,

import { Injectable } from '@angular/core';
import {User} from '../models/user.model';
import {Subject} from 'rxjs/Subject';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class UsersService {

  users: User[] = [];
  usersSubject = new Subject<User[]>();

  constructor() { }

  emitUsers(){
    this.usersSubject.next(this.users);
  }

  saveUsers(){
    firebase.database().ref('/users').set(this.users);
  }

  getUsers(){
    firebase.database().ref('/users')
    .on('value',(data)=>{
      this.users = data.val() ? data.val() : [];
      this.users.sort((a,b)=>a.ptsTotal-b.ptsTotal);
      this.emitUsers();
    });
  }

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441

1 Answers1

1

data.val() is not going to be an array. It's a going to be an object whose properties are the named the same as child keys under users (e.g. "-M9YJ..."). Those properties will further contain the data under each child.

If you need to sort by a child value, Realtime Database can actually do that for you using orderByChild() as described in the documentation. You don't need to sort in the client.

If you do still want to sort in the client, you will have to convert that object to an array somehow, then apply the sort to that new array.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Hello @Doug. Thank you, I'm almost sure that orderByChild is the good method to use. But it seems my id "M9YJ..." is a problem. When I'm doing orderByChild('ptsTotal') it's not working. And like I want all the users to establish a ranking I can't do an orderByChild('Id/ptsTotal'). What would be the solution ? – Alexandre Deschateaux Jun 12 '20 at 08:55