Rodney Mathew
Rodney Mathew

Reputation: 61

How to store data from firebaselistobservable to an array?

I'm trying to copy the data from firebase to an array using angular 2. But i'm unable to push the data into the array.

Here's the code:

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);  //PROBLEM HERE: Array agencyID is still 0.

    this.getTrackerData();

getAgencyData():

console.log("Fetching 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("Fetching 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),
        ));
    }    

Here is the debug console screenshot:

console screenshot

Since i'm a newbie to web programming some code may seem completely unnecessary.

What am I doing wrong in this code? How can I implement the same.

Upvotes: 4

Views: 1996

Answers (1)

alex kucksdorf
alex kucksdorf

Reputation: 2633

The problem is the location where, or better WHEN, you are checking the length of the array. You make an asynchronous call when you fetch the data, but you are checking the length of the array before the data has been returned. Therefore the array is still empty.

Try the following in getAgencyData():

console.log("Fetching 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("Array Length = ",this.agencyID.length); // See the length of the array growing ;)
    });
    // EDIT
    this.getTrackerData();
});

Upvotes: 4

Related Questions