I am very new to AngularFire. Trying to accomplish something similar to Angular ToH tutorial (e.g. retrieving/displaying a list and accessing item details by id) using AngularFireDatabase, the only way I found was:
I have been looking for days for a way to do this with a single request, with no result. Finally, I found a solution in #199 (closed):
At the time of item creation:
If I missed something in the documentation, I apologize for this issue. If not, I am very surprised that there is no simple way to retrieve items in a list with their reference.
If I am not wrong about it, I would either createPushId() to be documented or a simple way to retrieve list with items id. But using createPushId implies key redundancy in database, so it would not be the best solution in my opinion.
Angular: angular/[email protected]
Firebase: 4.12.1
AngularFire: 5.0.0-rc.5-next
It's not very clear in the documentation, but if you look in the example app here: https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md you will see the following code:
this.itemsRef = db.list('messages');
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
Then you have access to the key without storing it in the items....
Thank you @jymdman I finally made it work with your solution.
So I actually missed that in the doc, but I am still surprised we can only find this sample code in the "Deleting the entire list" section.
The most anodin use of angular lists is to display it and access individual items. The only way to do this is by using something similar to:
<div *ngFor="let item of items" (click)="doSomething(item.id)">
...
</div>
Personally, I think your sample code should be in a dedicated section and should be the first thing someone discovering AngularFire should see in the documentation.
Anyway, thank you a lot, it really helped.
this._db
.collection('collection')
.snapshotChanges()
.pipe(first())
.subscribe((res: DocumentChangeAction<any>[]) => {
res.forEach((result: DocumentChangeAction<any>) => {
const data = result.payload.doc.data();
this.extendedItems.push({
id: result.payload.doc.id,
data
})
});
});
Thanks for the hint. But in this case we have to navigate each items to parse the id. Do we have any other options to directly bind the items to Observable
Most helpful comment
It's not very clear in the documentation, but if you look in the example app here: https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md you will see the following code:
Then you have access to the key without storing it in the items....