Coder1000 Coder1000 - 24 days ago 9
Javascript Question

Why is my dataSnapshot.val() equal to null?

CODE:

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");

});





DATABASE:

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





QUESTION:

Why is my
dataSnapshot.val()
equal to
null
?

N.B.:

I want to order the posts by timestamp and query the 5 most recent.

Answer

You're storing the timestamps as strings, but passing in numbers.

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

Comparing strings to numbers won't work. If you pass in strings, it does work:

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");
});

Prints:

"5"

"THE VALUE:2, [object Object]"

"6"

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

For future questions: if you reproduce the problem in a jsbin, like I did for my answer, we'll both have the minimum code+json needed for your question within easy reach.