【问题标题】:AngularFire listen for child added添加了 AngularFire 监听子项
【发布时间】:2018-05-02 09:43:33
【问题描述】:

我想做的只是监听 child_added 事件以仅接收最后一个孩子。 这个想法是启动一个 Angular 应用程序 (appA),创建列表的引用,然后等待。

从其他应用程序 (appB),我可以在该列表中添加一个项目。

我希望 appB 对 appB 添加的项目做出一次反应

this.itemsRef = this.db.list('gpsAlerts');

this.itemsRef.snapshotChanges(['child_added'])
  .subscribe(actions => {
    actions.forEach(action => {
      console.log(action.type);
      console.log(action.key);
      console.log(action.payload.val());
    });
  });

但在 appA 启动时,我已经收到了列表中的所有项目。 而且,当我从 appB 添加项目时,该方法被多次调用。 我希望只得到最后一项。

我能做到吗?

非常感谢!

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    既然订阅了snapshotChanges,如果不想被多次调用,可以使用RxJS debounceTime()

    所以在你的情况下,它看起来像:

    ...
    import 'rxjs/add/operator/debounceTime';
    ...
    
    this.itemsRef.snapshotChanges(['child_added'])
      .debounceTime(500)
      .subscribe(actions => {
        actions.forEach(action => {
          console.log(action.type);
          console.log(action.key);
          console.log(action.payload.val());
        });
      });
    

    那么subscribe的作用域只会在最后一次调用后500ms被解释。

    【讨论】:

    • 感谢您的回复。但我仍然有同样的行为:-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2018-05-03
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多