Reputation: 18864
I'm developing an Angular2 application with Firebase as the datastore. The first step was to use a collection and to push objects into the collection:
this.weeks$ = angularFire.database.list("/weeks");
this.weeks$.push({
id: ScheduleComponent.weekId(),
});
I want now to delete a week from the collection. Do I have to query Firebase for the object and delete it? Or is there a way to delete an object from the ListObservable
directly?
Shouldn't be that difficult...
I've tried to query the database, but this deleted the entire collection:
this.angularFire.database.list('/weeks', {
query: {
id: weekId
}
}).remove();
Or do I have to use the filter operator on the ListObservable
to get the object and delete it? I'm trying the following:
this.weeks$
.find(week => week.id == weekId)
.do(
week => console.log(week)
// here the delete code
).subscribe();
But without expected results?
What am I doing wrong? I assume it's a combination of not knowing how to work with Firebase Angular 2 binding and not knowing how to properly handle rx observables.
EDIT
I've found a way to delete an object, but I'm still not satisfied with it: The template looks the following way:
<button class="btn btn-default (click)="deleteWeek(week.$key)">delete</button>
And the code:
this.angularFire.database.object(`/weeks/${weekId}`).remove();
How to delete an object without using it's Firebase key, e.g. on user input? And is it necessary to query again for the object? How to delete the object directly using the ListObservable
?
Upvotes: 2
Views: 2567
Reputation: 58410
You can remove elements from the list by passing them to remove
. For example, this would delete the first element:
this.weeks$ = angularFire.database.list("/weeks");
this.weeks$
.first()
.subscribe((list) => this.weeks$.remove(list[0]));
You can also pass preserved snapshots to remove
:
this.weeks$ = angularFire.database.list("/weeks", { preserveSnapshots: true });
this.weeks$
.first()
.subscribe((list) => this.weeks$.remove(list[0]));
You can also pass the push ID/key (which is made available by the thenable that's returned by push
) to remove
:
this.weeks$ = angularFire.database.list("/weeks");
let key = this.weeks$.push({
id: ScheduleComponent.weekId(),
}).key;
this.weeks$.remove(key);
The key is also available from the item itself:
this.weeks$ = angularFire.database.list("/weeks");
this.weeks$
.first()
.subscribe((list) => this.weeks$.remove(list[0].$key));
(Note that the code in this answer isn't indended to be sensible; it's just here to show how the values passed to remove
would be obtained.)
Upvotes: 2