根据时间查询 Firebase

Querying Firebase based on time

我正在尝试根据时间限制查询我的 Firebase。我正在关注 this blog post with this attached jsFiddle

问题是我得到了一个空白的 firebaseArray。

        var currentTime = (new Date).getTime();
        var twentyFoursHoursAgo = currentTime - 86400000;

        //scoresRef is defined as new Firebase(http://myfirebase.firebaseio.com/scores)
        scoresRef.on('value', function (dataSnapshot) {
        var summaryScores = $firebaseArray(scoresRef.orderByChild('timestamp').startAt(twentyFoursHoursAgo).endAt(currentTime));
        $scope.summaryScores = summaryScores;
        console.log(summaryScores);
        }

想法是,随着用户添加更多分数,数组将发生变化。然后我可以对其进行不同的数据操作(如平均值等)。这样,应用程序上就会显示 运行 24 小时平均值。

Firebase 中的数据如下所示:

我做错了什么?我知道数据在那里。

不确定这是否回答了您的问题,但看来我能做的最好的就是向您展示一些有用的东西。

查询时间戳范围

我添加了这个数据结构:

{
    "-Jy5pXbn5RpiK1-5z07O": {
        "timestamp": 1441076226561
    },
    "-Jy5pZJsYvsmv_dMtCtn": {
        "timestamp": 1441076173543
    },
    "-Jy5paWbkU6F8C6CEGpj": {
        "timestamp": 1441076181550
    },
    "-Jy5pbc0pJ1I5azenAi5": {
        "timestamp": 1441076247056
    },
    "-Jy5pfnMDKExW2oPf-D-": {
        "timestamp": 1441076204166
    },
    "-Jy5pgk55ypuG9_xICq-": {
        "timestamp": 1441076268053
    },
    "-Jy5phVgU2hDE_izcR8p": {
        "timestamp": 1441076271163
    },
    "-Jy5pilBteGhu05eMWQI": {
        "timestamp": 1441076215315
    }
}

然后用这个代码查询:

var ref = new Firebase('https://Whosebug.firebaseio.com/32321406');

var startAt = 1441076265715;
var endAt = startAt + 15000;

var query = ref.orderByChild('timestamp')
               .startAt(startAt)
               .endAt(endAt);
query.on('value', function(snapshot) {
    console.log(snapshot.val());
});

输出:

{
  -Jy5pgk55ypuG9_xICq-: {
    timestamp: 1441076268053
  },
  -Jy5phVgU2hDE_izcR8p: {
    timestamp: 1441076271163
  }
}

还有一条警告,我应该为 timestamp 添加索引规则。

jsbin: http://jsbin.com/qaxosisuha/edit?js,console

将数据集从 Firebase 绑定到 AngularJS

如果您尝试将查询结果绑定到 AngularJS 视图,您可以通过以下方式实现:

$scope.items = $firebaseArray(query);

使用 AngularFire 时 不要 尝试使用 console.log 来监控发生了什么。而是将其添加到您的 HTML:

<pre>{{ items | json }}</pre>

这将打印项目并在​​异步加载和更新数据时自动更新。

请注意,现在可能是了解 Firebase 的 AngularFire programming guide, which explains this last bit 和更多主题的好时机。