Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AngularFirebase Reference & Notes

My Notes on Typescript and AngularFirebase

Read & Manipulate A Document: i.e. Increment

Some Notes:

  • Need to import take and do from rxjs.
  • Use snapeshotChanges() instead of valueChanges()
  • take(1) so you do not end up in an infinite loop since you are editing the same object you are reading
  • DO NOT FORGET .subscribe() at the end.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/do';

interface Place {
  place_id:String,
  name:string,
  photo_reference:string,
  poppin:number,
}

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  private placeDoc: AngularFirestoreDocument<any>;
  private place: any;
  
  constructor(public navCtrl: NavController, private db: AngularFirestore) {
  }
  private incrementPlace(place_id){
    var placeDoc = this.db.doc<Place>("places/"+place_id);    
    var place:any = placeDoc.snapshotChanges().take(1).do(action => {
      console.log("snapshotChanges map",action.payload.exists,action.payload.data());
      if (action.payload.exists === false) {
        placeDoc.set({
          place_id : this.selectedPlace.place_id,
          name : this.selectedPlace.name,
          photo_reference : "",
          poppin: 1
        })
      } else {
        const data = action.payload.data() as Place;
        const id = action.payload.id;
        placeDoc.update({
          poppin:data.poppin+1
        })
        return { id, ...data };
      }
   }).subscribe();

   this.place = placeDoc.valueChanges();
  }
}


Appendix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.