代码之家  ›  专栏  ›  技术社区  ›  John

如何使用angularfire2实现child\u removed事件+

  •  0
  • John  · 技术社区  · 6 年前

    我正在用firebase+angularfire2测试google地图。

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

    “child\u removed”事件只返回操作,而不返回已删除的子项。 为removeMarkerUI方法实现“child\u removed”的最佳实践是什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   John    6 年前

    使用状态更改而不是快照更改

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