Last active
October 1, 2019 05:55
-
-
Save aslamanver/3b3dc79bc5548db9976c8379dbdcd5af to your computer and use it in GitHub Desktop.
Angular Firestore service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore'; | |
import { Observable } from 'rxjs/Observable'; | |
import { Item } from '../models/Item'; | |
@Injectable() | |
export class ItemService { | |
itemsCollection: AngularFirestoreCollection<Item>; | |
items: Observable<Item[]>; | |
itemDoc: AngularFirestoreDocument<Item>; | |
constructor(public afs: AngularFirestore) { | |
//this.items = this.afs.collection('items').valueChanges(); | |
this.itemsCollection = this.afs.collection('items', ref => ref.orderBy('title','asc')); | |
// For some versions | |
// this.items = this.itemsCollection.snapshotChanges().map(changes => { | |
// return changes.map(a => { | |
// const data = a.payload.doc.data() as Item; | |
// data.id = a.payload.doc.id; | |
// return data; | |
// }); | |
// }); | |
this.items = this.itemsCollection.snapshotChanges().pipe(map(s => | |
s.map(m => m.payload.doc.data() as Item) | |
)); | |
} | |
getItems(){ | |
return this.items; | |
} | |
addItem(item: Item){ | |
this.itemsCollection.add(item); | |
} | |
deleteItem(item: Item){ | |
this.itemDoc = this.afs.doc(`items/${item.id}`); | |
this.itemDoc.delete(); | |
} | |
updateItem(item: Item){ | |
this.itemDoc = this.afs.doc(`items/${item.id}`); | |
this.itemDoc.update(item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment