What is the best way to save data from a Firebaselistobservable into an array?

I've been attempting to transfer data from Firebase to an array using Angular 2, but I'm facing difficulties in pushing the data into the array.

Below is the code snippet:

Variables:

uid: string = '';
agencyItems: FirebaseListObservable<any[]>;
trackerItems: FirebaseListObservable<any[]>;
agencyID: any[] = [];

getData()

this.af.auth.subscribe(auth => {
        if (auth) {
            this.uid = auth.auth.uid;
        }
    });

    this.getAgencyData();

    console.log("AgentID: ",this.agencyID);   
    console.log("Array Length = ",this.agencyID.length);  //ISSUE HERE: AgencyID array still has a length of 0.

    this.getTrackerData();

getAgencyData():

console.log("Retrieving agency data");
    this.agencyItems = this.af.database.list('/agencies/',{preserveSnapshot:true});
    this.agencyItems.subscribe(snapshots => {
        snapshots.forEach(snapshot => {
            console.log(snapshot.val()._id);
            this.agencyID.push(snapshot.val()._id);
        });
    });

getTrackerData():

for (let i = 0; i < this.agencyID.length; i++)     
    {
        console.log("Retrieving Tracker data");
        this.trackerItems = this.af.database.list('/tracker/' + this.agencyID[i]);
        this.trackerItems.subscribe(trackerItems => trackerItems.forEach(Titem =>
            console.log("Tracker name: " + Titem.name),
        ));
    }    

Take a look at the debugging console screenshot here:

https://i.sstatic.net/haCGi.jpg

As a beginner in web programming, some parts of the code may seem unnecessary. Feel free to suggest improvements or point out mistakes.

What am I missing in this implementation? Any advice on how to rectify the issue would be highly appreciated.

Answer №1

The issue lies in the timing at which you are checking the array length within your code. Since you are making an asynchronous call to fetch data, the array is being checked for its length before the data has been fully returned, resulting in it being empty.

To address this problem, consider implementing the following changes inside the getAgencyData() function:

console.log("Retrieving agency data");
this.agencyItems = this.af.database.list('/agencies/',{preserveSnapshot:true});
this.agencyItems.subscribe(snapshots => {
    snapshots.forEach(snapshot => {
        console.log(snapshot.val()._id);
        this.agencyID.push(snapshot.val()._id);
        console.log("Current Array Length: ",this.agencyID.length); // Watch the array length increase :)
    });
    // UPDATE
    this.getTrackerData();
});

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

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

How to Delete an Item from an Array in BehaviorSubject Using Angular/Typescript

I have encountered an issue while trying to delete a specific element from my array upon user click. Instead of removing the intended item only, it deletes all elements in the array. I attempted to use splice method on the dataService object, but I'm ...

Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows: { "format": // file extn ----only xls "docTitle": //file name "document" :// base 64 encoded data } The attem ...

Tips for parsing and manipulating a json matrix array within Excel-VBA

Looking to convert JSON text into a JSON object in Excel-VBA, including a matrix/array that needs to be addressed (setting a VBA variable to the value). Previously, I successfully parsed nested/keyed JSON text using the "JsonConverter.parseJSON" method. H ...

Issue encountered on IIS 7.x server during deployment with HTTPS

Currently, I am running an Angular + .Net 4.5 fullStack application on IIS V7.5 with Windows Server. To conduct additional tests, I am using multiple instances of the same site with different versions of the application deployed on the same host. Each inst ...

Issue with Angular data display in template

My Ionic app with Angular is fetching data in the constructor, but I am facing difficulties displaying it in the HTML. Code component receiver: any; constructor( //.... ) { // get receiver data const receiverData = this.activatedRoute.snapsho ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

undefined is causing an error in React

Trying to display information on the UI, I am checking the status of IsMobileOnLease which is a child node in JSON. However, I am encountering an error that says "cannot read property of undefined react". If (this.mob.MobileLobList[0].MobileRiskList[0].I ...

Issue with <BrowserRouter>: TS2769: No suitable overload for this call available

I encountered this error and have been unable to find a solution online. As a beginner in typescript, I am struggling to resolve it. The project was originally in JavaScript and is now being migrated to TypeScript using ts-migrate. I am currently fixing er ...

Changing field visibility in Angular Reactive form (form validation) by toggling based on a checkbox in another component

I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the ch ...

Utilizing Next.js App Router to Enable Static Site Generation for Dynamic Routes in Live Environments

For my portfolio, I am utilizing Next.js's new App Router to highlight projects with dynamic routing (src/app/projects/[id]/page.tsx). During development, useSearchParams is able to correctly retrieve the project ID. However, in production, it returns ...

What types should you use for an Axios response in React and TypeScript?

Trying to display a basic user list fetched from an API, which returns the following data: [{"UserID":2,"FirstName":"User2"},{"UserID":1,"FirstName":"User1"}] Struggling to understand how to deal ...

Removing a contact from a telephone directory using C programming language

Struggling to remove a contact from my phone book code. All other functions are working fine, but deleting a contact is causing the program to stop. I've searched for different examples but haven't come across a solution that works for me. #inc ...

A guide on coding the source tag script for a payment form in CodeIgniter, specifically for a JavaScript form

Scenario: I have a variable called $data['tabdata'] that I am passing from controller C to view V. This variable includes a script element pointing to http://example.com/1.js. Problem: The script in 1.js is not running properly in the view. This ...

Exploring ways to test the ng-web-apis/geolocation Observable within an Angular 8 environment

I'm currently working on testing a basic Angular 8 service that utilizes the GeoLocation Service from Web APIs for Angular, which can be found at this link. public enableGPS() { if (!this.locationSubscription) this.locationSubscription = ...

Is it possible for prettier to substitute var with let?

One of the tools I utilize to automatically format my Typescript code is prettier. My goal is to find out if there is a way to have prettier replace all instances of 'var' with 'let' during the formatting process. Below is the script I ...

What is the best way to eliminate a particular element from an array produced using the .map() function in

I am experiencing an issue with my EventCell.tsx component. When a user clicks on the component, an event is created by adding an element to the components state. Subsequently, a list of Event.tsx components is rendered using the .map() method. The problem ...

The requested cast is invalid when converting SQL Server data to an array

Database: When attempting to transform SQL Server data into an array, I encountered an issue: Invalid specific cast error This is the code I used: string query = "select part1,part2,part3 from Table_3 where id ='" + textBox1.Text + "'"; int ...