What is the best way to organize the Firebase data that is stored under the user's unique

Hey there, I'm currently working on developing a leaderboard feature for an app. The idea is that users will be able to store their "points" in a Firebase database, linked to their unique user ID.

This is how the data is structured in JSON format:

- users
  - hJfEgXkyaKPckchL3kx8rpZ58Ew2
    -LV6c8E5rRD4_mQqsb6Q
      - name: "Lin Manuel Miranda"
      - points: 120
  - mlIBrdjT8CfIURQEAhLFPzzUFQg1
    -LV7I6d8LeuWFLH5MRKy
      - name: "Emily Blunt"
      - points: 200

The user IDs "mlIBrdjT8CfIURQEAhLFPzzUFQg1" and "hJfEgXkyaKPckchL3kx8rpZ58Ew2" are connected to their corresponding points stored in the database.

My current challenge is figuring out how to retrieve and display the list of users' points in ascending order. Any suggestions on how to modify the code to achieve this?

Below are snippets from my .ts and .html files:

import { Component } from '@angular/core';

// firebase imports
import * as firebase from 'firebase';
import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import { User } from 'src/models/login.interface';
import { Observable } from 'rxjs';
import { reference } from '@angular/core/src/render3';


@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  users: Observable<any>;

  constructor(
    private db: AngularFireDatabase
  ) {
    this.users = this.db.list('/users/').valueChanges();
    const usersRef = firebase.database().ref('/users/');
    const ref = usersRef.orderByKey();

    ref.once('value').then(function(snap) {
      snap.forEach(function (childSnap) {
        const pkey = childSnap.key;
        console.log(pkey);
      });
    });
  }
}
<ion-content>
    <div class="cards" *ngFor="let user of users  | async">
      <ion-card>
          <ion-card-header>
            <ion-card-title>{{user.name}}</ion-card-title>
            <ion-card-subtitle id ="points">{{user.points}}</ion-card-subtitle>
          </ion-card-header>
      </ion-card>
  </div>
</ion-content>

Currently, the .ts file is returning the user IDs instead of the points. Any guidance on how to tackle this issue would be highly appreciated. Thank you in advance!

Answer №1

Try replacing

const ref = usersRef.orderByKey();

with

const ref = usersRef.orderByChild('points');

in your query.

Update your angular fire code to reflect this change:

this.users = this.db.list('/users', ref => ref.orderByChild('points')).valueChanges()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

The constructor in a Typescript Angular controller fails to run

Once the following line of code is executed cockpit.controller('shell', shellCtrl); within my primary module, the shell controller gets registered with the Angular application's _invokeQueue. However, for some reason, the code inside t ...

Typescript input event

I need help implementing an on change event when a file is selected from an input(file) element. What I want is for the event to set a textbox to display the name of the selected file. Unfortunately, I haven't been able to find a clear example or figu ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Troubleshooting Vue 2 TypeScript Components Import Issue in VS Code

Has anyone experienced issues with TS pointing errors when importing custom components into a .vue file using the options api and webpack? The import is successful, everything works after bundling, but I'm still encountering annoying errors in the .vu ...

The Date Filter is causing a glitch in formatting the date value

I have a variable called dateSubmitted with the value of "dateSubmitted": "07-09-20:11:03:30" Currently, I am utilizing Angular Version 7 Within my HTML code, I am using the date filter to format the date like so: <td> {{element.dateSubmi ...

Using TypeScript to create a state object in Koa

I am currently utilizing Koa () as the framework for my backend, which consists of Node.js + TypeScript. Koa permits and recommends using the built-in `ctx.state` to store and pass data between different middleware functions. I have been adhering to this ...

Android's Edge browser now allows users to subscribe to web push notifications using the npm command, which will return an

Recently, I encountered a strange issue with the node.js web-push functionality that had been working flawlessly across different browsers and platforms. Everything was going smoothly on Chrome, Firefox, Opera, and even on Android, until I tested it on t ...

While attempting to index a nested object, TypeScript (error code 7053) may display a message stating that an element implicitly carries the 'any' type due to the inability to use an expression of type X to index type

I'm encountering an issue in TypeScript where I get the error (7053): Element implicitly has an 'any' type because expression of type X can't be used to index type Y when trying to index a nested object. TypeScript seems to struggle wit ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

How can I modify the appearance of folders in FileSystemProvider?

I have created an extension for vscode that includes a virtual filesystem with fake directories and files. While the extension is functioning properly, I am facing some challenges in customizing certain aspects due to lack of documentation. 1) I need to u ...

Visual Studio Code is unable to identify the TypeScript module located within the `node_modules` directory

After cloning the tslint repository, running npm install and grunt as instructed in the README, I opened the folder in Visual Studio Code (0.9.1). Upon inspecting a .ts file such as src/rules/typedefRule.ts, TypeScript errors appeared regarding the require ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

Encountering an issue with accessing a property in Angular's TypeScript module

I encountered an issue while trying to access a property of a static array that I created in a TypeScript class. The error message I received is as follows: ERROR TypeError: Cannot read property 'forbiddenProjectNames' of undefined Below is th ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

Tips on looping through a dynamic FormControl using Angular2 and FormBuilder

I am facing an issue when trying to iterate over a dynamically generated FormControl in the HTML section. Instead of displaying the expected values, I am getting [object Object],[object Object] in the input field. Here is the provided data structure: { ...

Sharing the input value with a service in Angular 4

I am a beginner when it comes to Angular 4. I currently have a variable named "md_id" which is connected to the view in the following way. HTML: <tr *ngFor="let item of driverData"> <td class="align-ri ...

Issue with Ionic ng-click not triggering

I am currently experimenting with an Ionic application that utilizes a Firebase backend. The issue I'm facing is that the ng-click="loginUser(user)" function does not seem to be triggering. When checking the console, it only displays Signed Out from ...

Is it possible to selectively mock certain components of an external module using jest?

I am totally new to using Jest, especially in regards to unit tests, and I am struggling to write a test for a specific scenario. I know that you can mock an external module like this.. jest.mock('@organisation/library', () => ({ Database: j ...

Hide react component by clicking it

There is a cookies component with a button labeled "I agree" that I want to use to close the component when clicked. However, I am facing an issue in getting this functionality to work. I understand that the onClick event on the button should trigger an ...