I need two functions to return all data as well as specific filtered data, but my constructs are wrong. Below is what "think" I want, but am returning Subscriptions instead of arrays:
allItems() {
var collectionAll: AngularFirestoreCollection<Item> =
this._afs.collection<Item>('items');
var itemArray$: Observable<Item[]> =
collectionAll.valueChanges();
// Returns Subscription but I need Items[]
return itemArray$.subscribe(items => {
return items;
})
}
specificItems(name: string) {
var collectionSpecific: AngularFirestoreCollection<Item> =
this._afs.collection<Item>('items', ref =>
ref.where('name', '==', name));
var itemArray$: Observable<Item[]> =
collectionSpecific.valueChanges();
// Returns Subscription but I need Items[]
return itemArray$.subscribe(items => {
return items;
})
}
Also I would think that it would need to be an async function, but the subscribe function doesn't return a promise.
And I'm not even sure at what point I would actually be charged a read count from Firestore...?
If you want a promise, you need to convert the Observable to a Promise using toPromise
:
specificItems(name: string): Promise<Item[]> {
var collectionSpecific: AngularFirestoreCollection<Item> =
this._afs.collection<Item>('items', ref =>
ref.where('name', '==', name));
var itemArray$: Observable<Item[]> =
collectionSpecific.valueChanges();
return itemArray$.toPromise();
}