Angularfire - Firebase 查询/同步文档中的前 x 项 [英] Angularfire - Firebase query / sync first x items in document

查看:21
本文介绍了Angularfire - Firebase 查询/同步文档中的前 x 项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 firebase.我有一个由 id 索引的 6 条记录的文档.我想查询并同步列表中的前 3 项.

I am just getting into using firebase. I have a document with 6 records indexed by id. I would like to query and sync the first 3 items in the list.

var metals = new Firebase("https://<dbname>.firebaseio.com/metals").limit(3);
$scope.metals = $firebase(metals);

这将提供列表中的最后 3 项.不是我想要的.

This provides the last 3 items in the list. Not what I wanted.

所以为了获得前 3 个项目,我认为这会起作用,但它坏了......

So to get the first 3 items, I thought that this would work, but it breaks...

var metals = new Firebase("https://<dbname>.firebaseio.com/metals").startAt(1).endAt(3);
$scope.metals = $firebase(metals);

我的数据结构:

{
  "metals" : [ null, 
    {
      "id" : 1,
      "metal" : "Aluminium",
      "element" : "Au" 
    }, {
      "id" : 2,
      "metal" : "Silver",
      "element" : "Ag"
    }, {
      "id" : 3,
      "metal" : "Copper",
      "element" : "Cu"
    }, {
      "id" : 4,
      "metal" : "Tin",
      "element" : "Sn"
    }, {
      "id" : 5,
      "metal" : "Nickel",
      "element" : "Ni"
    }, {
      "id" : 6,
      "metal" : "Iron",
      "element" : "Fe"
    }]
}

HTML 视图:

推荐答案

传入startAt的第一个参数 是优先级,而不是记录键.由于在这种情况下看起来您不需要键或优先级,因此您可以简单地使用以下语法来获取前三项:

The first parameter passed into startAt is a priority, not a record key. Since it doesn't look like you need a key or a priority in this case, you can simply this syntax to snag the first three items:

new Firebase(URL).startAt().limit(3)

此外,存储在示例数据的每条记录中的id"不是该记录的键,它只是数据中的另一个字段,也可能是foo"或任何其他任意名称,就查询而言被关注到.

Additionally, the "id" stored in each record of the example data is not the key for that record, it's just another field in the data and might as well be "foo" or any other arbitrary moniker, as far as querying is concerned.

当这些记录存储在 Firebase 中时,数组将转换为对象,并且索引用作每个条目的键.所以第一条记录的 id 将是 0,而不是 1.所以如果我想获取第二到第四条记录(例如你尝试的 1 到 3),我可以这样做:

When these records get stored in Firebase, the array is converted to an object, and the indices are used as the keys for each entry. So the first record's id would be 0, not 1. So if I wanted to grab the second through fourth records (e.g. 1 through 3 as you attempted), I could do this:

new Firebase(URL).startAt(null, 1).limit(3)

请仔细阅读数据列表文档和我们的博客关于阵列最佳实践;大多数情况下,您会希望避免使用这些 ID 并使用唯一 ID.

Please have a thorough read of the lists of data doc and our blog on array best practices; most of the time, you'll want to avoid those and use unique ids.

这篇关于Angularfire - Firebase 查询/同步文档中的前 x 项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆