使用 AngularFire 从 Firebase 中选择随机记录

编程入门 行业动态 更新时间:2024-10-26 17:33:17
本文介绍了使用 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:关键词]

本文发布于:2023-04-22 11:09:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AngularFire   Firebase

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!