0

I am testing google maps with firebase + angularfire2.

Firebase data structure

{
  markers: 
      key1 : {lat:1, lng:2}
      key2 : {lat:3, lng:4}           
}

with JS + firebase, all 3 events works well.

var markers = database.ref('markers');
markers.on('child_added',  function(snapshot) {
    addMarkerUI(snapshot);
});  
markers.on('child_changed', function(snapshot){
    updateMarkerUI(snapshot);
});
markers.on('child_removed', function(snapshot, prevChildKey) {
    removeMarkerUI(snapshot);
});  

But with angularfire2, it behaved very differently.

itemsRef: AngularFireList<any>;

constructor(private db: AngularFireDatabase) { }

ngOnInit() {
    this.itemsRef = this.db.list('markers');
    this.itemsRef.snapshotChanges(['child_added', 'child_changed', 'child_removed'])
        .subscribe(actions => {
            console.log(actions);
            actions.forEach(action => {
                if (action.type === 'child_added') {// works
                    console.log(action)
                    console.log(action.type);
                    console.log(action.key);
                }

                if (action.type === 'child_changed') {// works
                    console.log(action)
                    console.log(action.type);
                    console.log(action.key);
                }

                if (action.type === 'child_removed') {// does not works
                    console.log(action)
                    console.log(action.type);
                    console.log(action.key);
                }
                // this.items.push(action.payload.val());
                // console.log(action.payload.val());
            });
        });

"child_removed" event just returns actions without deleted child. What is the best practice to implement "child_removed" for removeMarkerUI method ?

John
  • 3,304
  • 1
  • 18
  • 26
  • This sounds like it might be a bug, can you build a repro on StackBlitz and post to our Github Issues? – James Daniels Mar 14 '18 at 19:03
  • @JamesDaniels I created it here https://stackblitz.com/edit/angular-um7hbv see console. I will report it to Github as well. – John Mar 15 '18 at 07:20

1 Answers1

1

use stateChanges not snapshotChanges

items: Observable<any[]>;
itemsRef: AngularFireList<any>;

constructor(private db: AngularFireDatabase) {}

ngOnInit() {
    this.items$ = this.db.list('markers');
    this.items$.stateChanges(['child_added', 'child_changed', 'child_removed'])
      .subscribe(action => {
        if (action.type === 'child_added') {
          console.log('I was added', action, action.payload.val())
        }

        if (action.type === 'child_changed') {
          console.log('I was modified', action, action.payload.val())
        }

        if (action.type === 'child_removed') {
          console.log('I was deleted', action, action.payload.val())
        }

      });
}
John
  • 3,304
  • 1
  • 18
  • 26