use*_*741 7 database angularjs firebase angularfire
有没有办法从firebase获取随机记录,如下所示:
{
"-JbmopNnshefBT2nS2S7" : {
"dislike" : 0,
"like" : 0,
"post" : "First post."
},
"-JbmoudijnJjDBSXNQ8_" : {
"dislike" : 0,
"like" : 0,
"post" : "Second post."
}
}
Run Code Online (Sandbox Code Playgroud)
我使用此代码来解决问题,但它下载了所有记录,因此如果DB更大,我的应用程序将非常慢:
HTML代码:
<div ng-controller="RandomCtrl">{{RandomPost.post}}</div>
Run Code Online (Sandbox Code Playgroud)
JS代码:
var app=angular.module('App', ['firebase']);
app.controller('RandomCtrl', function($scope, $firebase){
var ref = new Firebase("https://ind.firebaseio.com/");
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();
});
Run Code Online (Sandbox Code Playgroud)
您可以使用包含所有密钥的对象来解决大型数据库的问题,关于选取随机密钥,我认为您的做法很好。
我猜想的另一种方法是使用增量密钥,如 @lombausch 所说,然后您可以使用 key() 方法的组合来获取添加的最后一个密钥,然后根据最小值、最大值获取随机值。
这是保存增量/数字键的反模式: https://www.firebase.com/docs/web/guide/ saving-data.html#section-push
key() 方法参考: https://www.firebase.com/docs/web/api/firebase/key.html
| 归档时间: |
|
| 查看次数: |
2271 次 |
| 最近记录: |