使用 AngularFire 在 json 属性值上从 firebase 获取一条记录

Getting one record from firebase with AngularFire on json attribute value

我敢肯定这是一个非常简单的方法,但我是 Firebase 的新手,这让我很困惑。我在 Firebase 中有一个 JSON 树,如下所示:

{
  "games" : {
    "-LKZxsIcVe3Uixrdxdau" : {
      "id" : "thing1",
      "name" : "This is a thing"
    },
    "-LKZxt57WpCd8ARMr1Cy" : {
      "id" : "thing2",
      "name" : "This is another thing"
    },
    "-LKZxtm8udMhEyZ3tHd5" : {
      "id" : "thing3",
      "name" : "And yet another thing"
    }
  }
}

我知道我可以通过 firebase ID 获取一个对象:

this.theThing = this.db.object('/games/-LKZxtm8udMhEyZ3tHd5').valueChanges();

请问如何在 id 上获取单个对象?

我看到 how to query lists 使用 equalTo。这是这样做的方法吗?如果是这样,我如何 return 单个对象并将其分配给我的 this.theThing 变量,以便它也能实时更新等?

另外,这样查询效率高吗,还是我真的应该通过 Firebase ID 查询?

您需要使用list方法进行查询。

this.theThing = this.db.list('/games', ref => ref
  .orderByChild('id')
  .equalTo('thing3')
  .limitToFirst(1)
)
.valueChanges();

这不会将您的变量设置为对象 -LKZxtm8udMhEyZ3tHd5,而是将 this.theThing 设置为 Observable。您可能想要做的是将结果通过管道传输到 RxJs Promise 中以获得所需的结果,例如;

this.db.list('/games', ref => ref
  .orderByChild('id')
  .equalTo(someId)
  .limitToFirst(1)
)
.valueChanges()
.map(first())
.toPromise()
.then(snapshots => {
  this.theThing = snapshots[0];
});

这应该将 this.theThing 设置为所需的对象 -LKZxtm8udMhEyZ3tHd5。您将能够引用 this.theThing.id,它将 thing3 作为值。