The issue of Angular 4 Firebase Observable with .map() being duplicated upon refresh persists and reverting the order is not working

Utilizing Angular 4 alongside Firebase and AngularFire presents a question. How can I showcase the top 10 users from my database on the HTML code? Here is the snippet of code:

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

The structure of my Firebase database looks like this:

"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"
      }
  }

While navigating through my Angular 4 app, everything functions as expected. However, upon refreshing the page, I encounter an issue involving two console.log(a). One shows the reversed object while the other displays the original order. Consequently, my HTML showcases the data in the non-reversed format. Any suggestions on what could be causing this peculiar behavior? This only occurs when I refresh the page. Here is the output of console.log(a) after refreshing the page.https://i.sstatic.net/cLihQ.png

Answer №1

Upon conducting some experimentation, I have identified the root cause of the issue:

The crux of the matter lies in the fact that the .reverse() method not only produces a reversed array as output but also reverses the original array itself. Consequently, this alteration to the topusers array triggers the Observable to execute .map() once more, causing the array to revert back to its initial state.

To remedy this dilemma, simply modify the return statement to read as follows:

return topusers.slice().reverse();
. By utilizing the .slice() method, you generate a fresh copy of the array, effectively resolving this predicament.

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

Angular 4: Automatically dismiss modal once form submission process is complete

My Bootstrap 4 modal closes properly when I press the close button. However, I want the modal to close after submitting the create button in the form. I am using Angular 4. <div class="modal fade" id="createLabel" tabindex="-1" role="dialog" aria-label ...

What type will the click handler return be determined by TypeScript?

I am working on a custom button control that has a click handler which can either return a promise or void. Here is an example of the button options interface and the click handler: // --- Options for button control export interface buttonOptions { aPr ...

Trouble shooting: Angular 2 Http get request not firing

I'm facing an issue where nothing happens when I try to subscribe to my observable. There are no errors in the console or during the build process. Below is the code snippet that I am using: My service getBlueCollars(): Observable<BlueCollar[]& ...

Utilize the up and down arrow keys to scroll through a description list in React

If you want to navigate through the list of Description Details using the tab and shift tab keys, it can be done easily. The default behavior allows for smooth navigation. <dl> <dt style={{ textAlign: "center" }}>Beast of Bodmin< ...

Creating a secure connection on localhost with angular dart webdev: A step-by-step guide

Currently, I am developing a web application using Angular Dart. One issue I encountered is accessing the user's location feature through geolocation, as browsers like Chrome require HTTPS for this functionality. When deploying the web application, th ...

Using typescript, import the "anychart" library

After attempting to include the "anychart" library in my .ts file using the following import statement: import 'anychart'; I noticed that this line of code caused the entire HTML page on my local server to disappear. Here is a snippet from my ...

Having trouble connecting JSON data to an Angular 4 object

I am having trouble with rendering a JSON object in the *ngFor loop. Component: @Input() users: Observable<IUser>; this.users = this.getUserByRole(this.role); getUserByRole(role) { return this._searchService.getUsersByRole(role); } ...

What is the best way to calculate the difference between two dates using Angular?

How can I subtract two variables of type Date in Angular? Is there a built-in method for this, or do I need to create my own? This is what I have attempted: test: Date = new Date(); var1: Date = new Date('20-08-2018'); var2: Date = new Da ...

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Can you please explain to me the purpose of the ncu -u command?

Struggling to update my Angular project in Visual Studio to a specific version of Angular. Instead of following the tutorial that provided me with the latest Angular version, I wanted to install version 6 specifically. So, I ran npm install -g @angular/ [ ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

Redirecting a subdomain to an internal path on Azure Static Web App

I am currently managing an Angular application with Azure static web app. Is there a way to redirect a subdomain to an internal path? For example: abc.mydomain.com to mydomain.com/abc I have set up the CNAME in my DNS, but have unsuccessfully tried using ...

The Angular 2.0 HTTP post request encountered an error when trying to respond with a status of 200 Ok for a null

I'm currently attempting to post data using http in Angular 2. I have added an http call with the corresponding API, and when I click the button, it should send data to my database. However, an error is showing up in the console. XMLHttpRequest canno ...

Leveraging thousands of on() event listeners in Firebase demonstrates exceptional design

We are looking to perform operations on our Firebase database and modify data based on user input from their mobile devices by changing a flag. Currently, we are using the `on()` method to listen to specific flags within each user's node. This listen ...

Exploring the capabilities of ExcelJS for reading xlsx files within an Angular environment

I'm trying to access a source file, make some changes to it, and then provide it for the user to download. However, I am facing an issue with reading the source file from my project directory. Below is my implementation using excelJS for file reading: ...

Inject the type into the dependency container

I am managing multiple databases without relying on ORM tools. Here, I will demonstrate an example using Postgres and MSSQL databases with UserQueries. https://i.sstatic.net/GFs5D.png Within my codebase, I have an interface called IDataBase which is impl ...

Create a streaming service that allows for multicasting without prematurely ending the main subject

In my implementation of caching, I am utilizing BehaviorSubject and multicast. The cache stream should begin with an HTTP request and I want the ability to manually trigger a cache refresh by calling next on the subject. While the conventional method of us ...

Retrieving URLs of bulk uploaded images using ReactJS and Firebase

I am facing an issue with my current state setup where I am storing an array of images. The problem arises when I try to upload each image to Firebase by iterating through the array. Despite using getDownloadURL() in each iteration, it consistently retur ...

Establishing the testing sequence for Angular 8

I've been encountering a frustrating issue where one of my tests fails at random intervals. To add some order to the debugging process, I attempted to set a seed number in the 'karma.conf.js' file and also tried setting 'random: false&a ...

Implement deferred loading of Stripe <script> in components using ElementRef

Does anyone know a way to lazy load a section of a website that uses Stripe for payment? I don't want to include the <script> tags in the index.html file since it may not always be used and could just add unnecessary bandwidth. I came across th ...