簡體   English   中英

從Firebase實時數據庫(Angularfire 5和Ionic 3)中檢索單個值

[英]Retrieve single value from Firebase Real Time Database (Angularfire 5 and Ionic 3)

我希望能夠使用實時數據庫(RTD)條目中的單個值。 使用Firestore,我可以使用以下代碼:

interface Led{
  currentState: boolean,
  lightSensor: number
}

currentState: boolean;
lightSensor: number;

this.afs.collection('Led').valueChanges().subscribe((Led: any) => {
  this.lightSensor = Led[0].lightSensor;
  this.currentState = Led[0].currentState;
})

然后,我可以將currentState或lightSensor調用為HTML並顯示值。 我可以找到的所有RTD示例都使用ngFor並顯示JSON數據,我不知道如何從該數據中獲取單個值。 我嘗試了以下內容,這些內容基本上是從Firestore代碼復制而來的:

this.db.list('leafBox001').valueChanges().subscribe((Led: any) => {
  this.currentState = Led[0].currentState;
  console.log(this.currentState);
});

控制台日志返回未定義。

您可以通過鍵獲取對象:

this.db.object(`leafBox001/${id}`).valueChanges()

我認為這僅僅是我對這種語言的不熟悉。 這是我在尋找的答案https://stackoverflow.com/a/47877360/9971934

遵循方法示例:

getCategory(idCategoria:string) {
  this.refCategoria = this.db.list('categorias',

  ref => ref.orderByChild('id').equalTo(idCategoria));

  this.refCategoria.valueChanges().subscribe(

    (datas) => { console.log("datas", datas) }
  );

}

這是過濾器:

ref.orderByChild('id').equalTo(idCategoria))

我集合的'id'=>字段用於索引數據。 'idCategoria'=>這是我的RTDB中注冊表的“ id”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM