How to store data from firebaselistobservable to an array?

前端 未结 1 1901
旧时难觅i
旧时难觅i 2021-01-19 08:44

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

相关标签:
1条回答
  • 2021-01-19 09:13

    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();
    });
    
    0 讨论(0)
提交回复
热议问题