【问题标题】:Firebase JavaScript / AngularFire - How Do I Get the Last Added Property of an Watched Object?Firebase JavaScript / AngularFire - 如何获取被监视对象的最后添加属性?
【发布时间】:2017-05-16 03:31:09
【问题描述】:

我有一个 Firebase 对象,如下所示:

-notifications
    -1-1-2017 1:08:22 PM
        -message: 'test'
        -timestamp: 1483294112
    -1-1-2017 1:08:23 PM
        -message: 'two'
        -timestamp: 1483294113
    -1-1-2017 2:08:22 PM
        -message: 'three'
        -timestamp: 1483294473

我不断将新属性推送到notifications 对象中,其中键是日期时间。

如果我有如下所示的$watch,如何获取附加到notifications 对象的最新属性?

var ref = new Firebase(firebaseConstants.url + 'notifications');
var sync = $firebase(ref);
$scope.notifications = sync.$asArray();
$scope.$watch('notifications', function(){
    ......
});

我想避免在$scope.notifications 上运行循环来找出新旧值之间的差异。

Firebase JS API 或 AngularFire 库是否有内置方式来执行此操作?

【问题讨论】:

    标签: firebase firebase-realtime-database angularfire


    【解决方案1】:

    好吧,看来您使用的是过时版本的 angularfire。我的回答将基于最新版本(2.2.0)。但是,根据此答案,我将在此处使用的所有功能自 1.0.0 以来都已可用:https://stackoverflow.com/a/28896261/6162666

    由于您要求使用内置方法来执行此操作,因此我不会尝试仅根据 $scope.$watch 给出答案。 Angularfire 对象和数组已经支持 $watch 方法很长时间了。您可以简单地在 $firebaseArray 上调用 $watch,它会在新事件发生时告诉您。

    请注意,$watch 是在您的 $firebaseArray/$firebaseObject 上调用的,而不是在您的 $scope 上。

    说了这么多,如果您将代码转换为最新版本的 angularfire,它看起来像这样:

    var ref = new Firebase(firebaseConstants.url + 'notifications');
    var notifications = $firebaseArray(ref);
    notifications.$watch(function(events){
       console.log(events); //Logs all the child_added events when new notifications are pushed
    });
    

    相比之下,docs 中给出的例子如下:

    var list = $firebaseArray(ref);
    
    list.$watch(function(event) {
      console.log(event);
    });
    
    list.$remove("foo");
    // logs { event: "child_removed", key: "foo" }
    
    list.$add({ hello: "world" });
    // logs { event: "child_added", key: "<new_id>", prevId: "<prev_id>" }
    

    稍后,您可以调用 $destroy() 停止监听更改。

    我应该指出,这只会在添加新 ID 时向您显示,这似乎正是您所需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      相关资源
      最近更新 更多