简体   繁体   中英

Get data from firestore and put into array in Ionic

I am creating an app in angular, and one task is, I need read data from Firestore and save into an array, my code snippet is as below:

 public getListingData(): Observable < RequestListingModel > { console.log("getting listing..."); this.firestore.collection('Requests').snapshotChanges().subscribe( requests => { this._listRequestItems = requests.map(a => { const data = a.payload.doc.data() as RequestItemModel; data.requestId = a.payload.doc.id; console.log("doc found - " + data.requestId); return data; }) }); const requestListingModel = { items: this._listRequestItems } as RequestListingModel; return of(requestListingModel); } 
And my code of RequestListingModel is as below:

 import * as dayjs from 'dayjs'; export class RequestItemModel { name: string; address: string; category: string; requestId: string; postBy: string; description: string; // Default mock value // expirationDate = '12/01/2018'; expirationDate: string = dayjs().add(5, 'day').format('MM/DD/YYYY HH:mm:ss') as string; } export class RequestListingModel { items: Array<RequestItemModel> = []; constructor(readonly isShell: boolean) { } } 

And it's not working as I always get empty return when call the function getListingData(), but the console can print out the each requestId successfully, I think something wrong with the way I store into array, please help, thanks!

Your problem is happening because things are happing asynchronously:

So return of(requestListingModel); gets called before this.firestore.collection('Requests').snapshotChanges().subscribe(...) populates the array, thus returning an observable of an empty array.

Since it looks like you want to return an observable, don't subscribe() inside your method. Just do a map() on the snapshotChanges observable to transform the output, and let the consuming code subscribe to your getListingData() method.

public getListingData(): Observable < RequestListingModel > {
    console.log("getting listing when someone subscribes...");


    return this.firestore.collection('Requests').snapshotChanges().pipe(
        map(requests => { 
            let requestListingModel = {
                items: []
            } as RequestListingModel;

            requests.map(a => {
                let data = a.payload.doc.data() as RequestItemModel;
                data.requestId = a.payload.doc.id;

                console.log("doc found - " + data.requestId);

                requestListingModel.items.push(data);
            });

            return requestListingModel;
        })
    );
}

Note: still... can't test this at the moment, so it may not be 100% correct :-\\
But hopefully points you in the right direction. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM