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

Firebase JavaScript/AngularFire-如何获取监视对象的最后添加属性?,firebase,firebase-realtime-database,angularfire,Firebase,Firebase Realtime Database,Angularfire,我有一个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'

我有一个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
对象中,其中键是datetime

如果我有一个如下所示的
$watch
,如何获取附加到
通知
对象的最新属性

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
});
相比之下,本节中给出的示例如下:

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>" }
var list=$firebaseArray(ref);
列表。$watch(功能(事件){
console.log(事件);
});
列表。$remove(“foo”);
//日志{event:“child_removed”,key:“foo”}
列表。$add({hello:“world”});
//日志{事件:“添加了子项”,键:,prevId:}
稍后,您可以调用$destroy()停止侦听更改

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