【问题标题】:Why is my dataSnapshot.val() equal to null?为什么我的 dataSnapshot.val() 等于 null?
【发布时间】:2016-11-16 15:58:43
【问题描述】:

代码:

app.controller('ctrl', function ($scope, $firebaseArray, $timeout) {

    $scope.data = [];
    var _start = 0;
    var _end = 4;
    var _n = 5;

    console.log("1");

    $scope.getDataset = function() {
        console.log("4");
        fb.orderByChild('time').startAt(_start).endAt(_end).limitToLast(_n).on("value", function(dataSnapshot) {
            console.log("5");
            $scope.data.push(dataSnapshot.val());
            console.log("THE VALUE:"+dataSnapshot.val());
            console.log("6");
        });

        console.log("7");


        _start = _start + _n;
        _end = _end + _n;

        console.log("8");
    };

    console.log("2");

    $scope.getDataset()

    console.log("3");

});

数据库:

"posts" {
    "fun" {
         "-Kzugwouzgafsdbkuzbf" {
             "time": 1478443829263
         }
         "-Krugwouzgafawdrawdr" {
             "time": 1478446164691
         }
    }
}

问题:

为什么我的dataSnapshot.val() 等于null

注意:

我想按时间戳排序帖子并查询最近的 5 个。

【问题讨论】:

  • 请包含重现问题所需的最少、完整信息(JSON + 代码)。因此,您查询的实际数据以及带有_start_end_n 的硬编码值的查询。
  • @FrankvanPuffelen 完成。
  • 谢谢。现在还请提供所需的最小实际 JSON。最后:你如何确定snapshot.val()null?您共享的代码中没有任何内容显示其价值。
  • 完成。至于JSON,我会更新数据库文本。
  • @FrankvanPuffelen 现在全部完成 :)

标签: javascript angularjs firebase firebase-realtime-database angularfire


【解决方案1】:

您将时间戳存储为字符串,但传入数字。

"time": "1456273845127"
var _start = 0;

无法将字符串与数字进行比较。如果你传入字符串,它确实有效:

fb.orderByChild('time').startAt("0").endAt("4").limitToLast(5).on("value", function(dataSnapshot) {
    console.log("5");
    console.log("THE VALUE:"+dataSnapshot.numChildren()+', '+dataSnapshot.val());
    console.log("6");
});

打印:

“5”

“值:2,[对象对象]”

“6”

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

对于未来的问题:如果您在 jsbin 中重现问题,就像我在回答中所做的那样,我们都将拥有您的问题所需的最少代码 + json。

更新

由于您表示将时间戳存储为数字,因此对行为的解释有所不同。在对数值进行排序/过滤时,Firebase 将进行数值比较。当前时间戳比您在代码中使用的4 大得多。

fb.orderByChild('time').startAt(0).endAt(Date.now()).limitToLast(5).on("value", function(dataSnapshot) {
    console.log("5");
    console.log("THE VALUE:"+dataSnapshot.numChildren()+', '+dataSnapshot.val());
    console.log("6");
});

这又给了我两个项目的列表:

“5”

“值:2,[对象对象]”

“6”

【讨论】:

  • 糟糕。我的错:时间戳实际上是整数,而不是字符串:/
  • 我刚刚意识到我误用了 startAt 和 endAt。立即修复。
猜你喜欢
  • 2018-10-08
  • 2010-12-22
  • 2020-04-27
  • 2011-03-09
  • 2023-03-19
  • 2022-11-21
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多