且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取 firebase 返回的数组长度

更新时间:2023-01-17 19:37:27

请记住,调用 $asArray 是一个异步操作.

Keep in mind that calling $asArray is an asynchronous action.

$scope.notes = $firebase(ref).$asArray();
console.log($scope.notes.length); // the data has not loaded yet

您在控制台中看到零长度的原因是因为值可能会在日志缓冲和打印之间发生变化,这可能会产生误导.尝试使用断点查看执行时的值.

The reason why you're seeing a zero length in the console is because values can change between buffering of the log and printing it, which can be very misleading. Try using a breakpoint to see the values as they execute.

由于数据是异步的,您需要使用 $loaded 承诺.

Since the data is asynchronous you'll need to use the $loaded promise.

$scope.notes.$loaded().then(function(notes) {
   console.log(notes.length); // data is loaded here
});