How to store data from firebaselistobservable to an array?

I am trying to copy data from firebase to an array using angular 2. But I cannot output the data to an array.

Here is 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 a screenshot of the debug console:

console screenshot

Since I'm new to web programming, some code may seem completely unnecessary.

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

+4
source share
1 answer

, , . , , . .

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

Source: https://habr.com/ru/post/1669249/


All Articles