Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@samuelstevens9
Last active March 10, 2018 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelstevens9/6b78846bdba507d8ee46212518ec05f7 to your computer and use it in GitHub Desktop.
Save samuelstevens9/6b78846bdba507d8ee46212518ec05f7 to your computer and use it in GitHub Desktop.
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