Skip to content

Instantly share code, notes, and snippets.

@aslamanver
Last active October 1, 2019 05:55
Show Gist options
  • Save aslamanver/3b3dc79bc5548db9976c8379dbdcd5af to your computer and use it in GitHub Desktop.
Save aslamanver/3b3dc79bc5548db9976c8379dbdcd5af to your computer and use it in GitHub Desktop.
Angular Firestore service
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