AngularFire 在只有新 post 到达时观看

AngularFire watch when only new post arrived

我想在新 post 到达时通知我的 Web 应用程序用户,而无需他们刷新页面。我正在使用 firebase 和 angularfire 作为包装器。

这是我的代码:

var query = Refs.getDeptRef("IT").orderByChild("timestamp").limitToLast(25);    
var talks = $firebaseArray(query);
    talks.$watch(function (e) {
                alert('new post arrived');
            });

上面的代码在新 post 到达时有效,但是,当我刷新页面(或第一次加载页面)时,警报弹出数百次!如何让它在页面加载后只观看新的 posts?感谢您的评论。

您可以使用 $loaded():

Returns a promise which is resolved when the initial array data has been downloaded from the database. The promise resolves to the $firebaseArray.

然后在检索到初始数据后使用$watch

例如:

var query  = Refs.getDeptRef("IT").orderByChild("timestamp").limitToLast(25);

var talks = $firebaseArray(query);

talks.$loaded().then(function(initialData) {

  console.log(initialData);

  talks.$watch(function(data) {

    console.log(data);
  });
});