Firebase JavaScript / AngularFire - 如何获取监视对象的最后添加 属性?

Firebase JavaScript / AngularFire - How Do I Get the Last Added Property of an Watched Object?

我有一个 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 库是否有内置方法来执行此操作?

嗯,看来您使用的是过时版本的 angularfire。我的回答将基于最新版本(2.2.0)。但是,根据以下答案,我将在此处使用的所有功能自 1.0.0 以来就可用:

由于您要求使用内置方法来执行此操作,我不会尝试仅基于 $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,这似乎正是您所需要的。