Removing an item in a list

A list in Firebase looks something like this when looking at the database from the Firebase console:

books {
0 : 'tomato',
1: 'cucumber'
}

Of course, there is an internal representation of each item that points to a key with a hash value. We have the following scenario; we want to delete the first item in the list. We write some code that looks like this:

this.angularFireDatabase.list('/books').remove(<key>)

It's now that we discover that we don't know what the key is for the item we want to remove. This is where we start using the method snapshotChanges() and try to find this out:

this.angularFireDatabase
.list('/books')
.snapshotChanges()
.subscribe( list => {
console.log('list',list);
})

The list parameter is a list, but the list items is a complicated object that contains the key we need as well as the value that we mean to display in the UI. We realise that this is the way to go and decide on using a map() function on our stream to transform the it into a list of books.

First off, we amend our book.model.ts file to contain a key property, like so:

export class Book {
title: string;
key: string;
constructor(json) {
this.title = json.payload.val();
this.key = json.key;
}
}

We can see that we needed to change how we access data; our data was to be found under the payload.val() and our key was easy to retrieve. With this knowledge, we can now build a list :

@Component({})
export class BookComponent {
books$:Observable<Book[]>

constructor(private angularFireDatabase:AngularFireDatabase){
this.books$ = this.angularFireDatabase
.list('/books')
.snapshotChanges()
.map(this.mapBooks);
}

private mapBooks(data): Book[] {
return data.map(json => new Book(json));
}

remove(key) {
this,books$.remove(key);
}

In the following code snippet, we loop all the books in the list and create a remove button for each book in the list. We also wire up each remove button to point to the book.key, that is, our key, which is what we need when communicating a remove action to Firebase:

<div *ngFor="let book of books | async">
{{ book.title }}
<button (click)="remove(book.key)">Remove</button>
</div>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset