【问题标题】:How can I implement child_removed event with angularfire2 +如何使用 angularfire2 + 实现 child_removed 事件
【发布时间】:2018-03-14 08:57:59
【问题描述】:

我正在使用 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());
            });
        });

"child_removed" 事件只返回没有删除子项的操作。 为 removeMarkerUI 方法实现“child_removed”的最佳做法是什么?

【问题讨论】:

  • 这听起来可能是一个错误,你能在 StackBlitz 上构建一个 repro 并发布到我们的 Github 问题吗?
  • @JamesDaniels 我在这里创建了它stackblitz.com/edit/angular-um7hbv 见控制台。我也会向 Github 报告。

标签: firebase angularfire2 angularfire5


【解决方案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())
        }

      });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 2015-09-09
    • 2019-06-13
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多