如何使用angularfire2 +实现child_removed事件

时间:2018-03-14 08:57:59

标签: firebase angularfire2 angularfire5

我正在使用firebase + angularfire2测试谷歌地图。

Firebase数据结构

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

使用JS + firebase,所有3个事件都运行良好。

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);
});  

但是对于angularfire2,它表现得非常不同。

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());
            });
        });

&#34; child_removed&#34; event只返回没有删除子节点的动作。 实施&#34; child_removed&#34;的最佳实践是什么? for removeMarkerUI方法?

1 个答案:

答案 0 :(得分:1)

使用stateChanges而不是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())
        }

      });
}