【问题标题】:How to get all root children in Firebase using TypeScript and Ionic 3?如何使用 TypeScript 和 Ionic 3 在 Firebase 中获取所有根子节点?
【发布时间】:2018-08-25 19:04:36
【问题描述】:

我有这个 Firebase 数据库:

我需要获取 alii-b9d94 的所有 uid(子代)。但问题是:当我将它作为对象获取时,我无法访问该对象以从中获取值。

这是我能够获得但无法访问的内容:

ts 代码:

    import { Component } from '@angular/core';
    import { IonicPage, NavController, NavParams } from 'ionic-angular';

    import firebase from 'firebase';

    import { AuthService } from '../../services/auth';
    import { InfoService } from '../../services/info';


   @IonicPage()
   @Component({
selector: 'page-dash',
templateUrl: 'dash.html',
})

 export class DashPage {


     constructor(public navCtrl: NavController,
          public navParams: NavParams,
          private infoService: InfoService,
          private authService: AuthService) {

            firebase.database().ref().on('value', (snap) => {

            let rootVals = snap.val();
            let uids : string[] = [];

          /* I am trying to access this by this code but not working :(
   I knew the problem with .this but Is there any other way i can through it 
            retrieve every child in a single variable */

            console.log(rootVals.this.uids); 


            console.log("rootVals");
            console.log(rootVals);

          } );
}

}

如何获取每个孩子并将其存储在单个变量中?

【问题讨论】:

    标签: typescript firebase firebase-realtime-database ionic3


    【解决方案1】:

    要仅获取密钥(uids),请尝试以下操作:

    firebase.database().ref().on('value', (snap) => {
    snap.forEach(child => {
    let keys=snap.key;
      });
    });
    

    更多信息在这里:

    https://firebase.google.com/docs/reference/js/firebase.database.Reference#key

    【讨论】:

      【解决方案2】:
      let uids = [];
      let rootVals = [];
      
      firebase.database().ref().on('value', (snap) => {
          let result = snap.value();
          for(let k in result){
           uids.push(k);
           rootVals.push(result[k]);
          }
      });
      

      "snap.value()" 同时拥有 key 和 value 对象,所以像这样使用 for 循环,可以分别获取对象的 key 和 value。

      每次 for 循环运行时,“k”都会给出对象键。这样您就可以获得每个对象的所有键。 "result[k]" 也给出了值对象。

      如果需要同时获取key和value,可以制作自己的json对象并push到数组中

      let keys_values = []
      firebase.database().ref().on('value', (snap) => {
          let result = snap.value();
          for(let k in result){
            keys_values.push({
              key : k,
              values : result[k]
            })
          }
      });
      

      【讨论】:

      • 虽然这段代码可能会回答这个问题,但最好还是解释一下代码的作用以及它如何解决问题。
      • @BrettDeWoody 我已经编辑了代码。感谢您的建议!
      猜你喜欢
      • 2018-09-22
      • 2012-07-13
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 2015-07-20
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多