inconsistency in lists.md docs
The current version of the docs (844c096) https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md strongly implies that the .valueChanges() does not return the key of the items in the list, only the data associated with the key (emphasis added):
What is it? - Returns an Observable of data as a synchronized array of JSON objects. All Snapshot metadata is stripped and just the method provides only the data.... When would you not use it? - When you need a more complex data structure than an array or you need the key of each snapshot for data manipulation methods. This method assumes you either are saving the key for the snapshot data or using a "readonly" approach.
However, the example app
<li *ngFor="let item of items | async">
<input type="text" #updatetext [value]="item.text" />
<button (click)="updateItem(item.$key, updatetext.value)">Update</button>
<button (click)="deleteItem(item.$key)">Delete</button>
</li>
...
constructor(db: AngularFireDatabase) {
this.itemsRef = db.list('messages');
this.items = this.itemsRef.valueChanges();
}
seems to rely on valueChanges() returning a key (to pass into the button click handlers).
This is slightly confusing.
Same fundamental issue in #1234
Based on what I understood from the documentation if you need the $key then we should use snapshotChanges() so I think that the constructor in the example should be like this
constructor(db: AngularFireDatabase) {
this.itemsRef = db.list('messages');
this.itemsRef.snapshotChanges().map(actions => {
return actions.map(action => {
const data = action.payload.val();
const $key = action.payload.key;
return { $key, ...data };
});
}).subscribe(items => {
this.items = items;
});
}
let me know if I'm right or if we are able to access the key using valueChanges()
I made a PR #1237
can someone post sample code on how to update/delete items, like the example app in https://github.com/angular/angularfire2/blob/master/docs/rtdb/lists.md is trying to do?
Stackblitz Template Example - Remember to set your Firebase configuration in app/app.module.ts.
@jacobnaran
i did have that, thanks @elmergu . my problem is that i still can't figure out how to edit or delete a specific item; i can create and read, though.
edit: oh i just saw that example you linked. i will try it out!
this.groupsRef = this.afDatabase.list('/Groups');
this.groups = this.groupsRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
Visual studio code gives an error that Object is possibly 'null' for key: c.payload.key and ...c.payload.val()
look like, if you just need data, you have to use "valueChanges", but if you need update or delete item in list, you have to subscribe on "snapshotChanges" object, am I right ?!
@hiepxanh You are right.