如何将数据从firebaselistobservable存储到数组?

时间:2017-02-09 09:43:06

标签: arrays angular typescript firebase

我尝试使用角度2将数据从firebase复制到数组但是我无法将数据推送到数组中。

以下是代码:

变量:

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

以下是调试控制台屏幕截图:

console screenshot

由于我是网络编程的新手,因此某些代码似乎完全没必要。

我在这段代码中做错了什么?我该如何实现它。

1 个答案:

答案 0 :(得分:3)

问题是您在检查阵列长度时的位置或更好的位置。在获取数据时进行异步调用,但是在返回数据之前检查数组的长度。因此数组仍然是空的。

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