本文介绍了使用 AngularFire 从 Firebase 中选择随机记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号..有没有办法像这样从 firebase 获取随机记录:
Is there any way to get random record from firebase like this:
{
"-JbmopNnshefBT2nS2S7" : {
"dislike" : 0,
"like" : 0,
"post" : "First post."
},
"-JbmoudijnJjDBSXNQ8_" : {
"dislike" : 0,
"like" : 0,
"post" : "Second post."
}
}
我用这段代码解决了这个问题,但它下载了所有记录,所以如果数据库更大,我的应用程序会运行得很慢:
I used this code to solve the problem, but it download all records, so if DB would be bigger, my app will work very slow:
HTML 代码:
<div ng-controller="RandomCtrl">{{RandomPost.post}}</div>
JS代码:
var app=angular.module('App', ['firebase']);
app.controller('RandomCtrl', function($scope, $firebase){
var ref = new Firebase("https://ind.firebaseio/");
var sync=$firebase(ref);
$scope.messages = sync.$asArray();
$scope.GetRandomPost=function(){
return $scope.RandomPost=$scope.messages[Math.floor(Math.random()*$scope.messages.length)];
};
$scope.GetRandomPost();
});
推荐答案
您可以将 startAt 与您自己的增量索引一起使用.例如,假设您的记录中有索引(0 到 n).
You can use startAt with your own incremental index. For example, suppose you have index (0 to n) in your records.
做这个查询:orderByChild("index").startAt(rint).limitToFirst(1);
Do this query: orderByChild("index").startAt(rint).limitToFirst(1);
查看代码片段:
var rint = Math.floor((Math.random() * 10)) // you have 10 records
var query = ref.orderByChild("index").startAt(rint).limitToFirst(1);
var results = $firebaseArray(query);
results.$loaded(
function(x) {
// let's get one
$scope.oneResult = x[0];
}, function(error) {
console.error("Error:", error);
});
};
这篇关于使用 AngularFire 从 Firebase 中选择随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论