访问Firebase中的2个关键数据

时间:2018-06-17 11:03:21

标签: javascript firebase firebase-realtime-database

我可以访问密钥的第一个数据,但无法访问密钥路径的下一个数据。当我输入' value'而不是' child_added'我获取第一条路径的数据,但我需要访问phot

中显示的路径中的所有数据
    class App extends Component {
      constructor(props) {
        super(props)
        this.state = {
          users: []
        }
        this.exportFile = this.exportFile.bind(this)
    }

    componentWillMount(){
      this.getUsers()
      this.getdataIDs()
    }

    getUsers() {
      let users = []

      // uncommented line gives an error
      /*var eventID = firebase.database().ref(`conversationEnrolments`).once('value')*/
      var path = firebase.database().ref(`conversationEnrolments`)
      path.once('child_added', snapshot => {
         snapshot.forEach(snap => {
         users.push(snap.val())
      })
      this.setState({
        users
      })
    })
   }

the values of the last path are not displayed

1 个答案:

答案 0 :(得分:2)

您的问题来自于once()方法“只侦听指定事件类型的一个事件,然后停止侦听。”详见文档here

所以这就是为什么你只得到一个孩子的价值,即-LDHYq... id的那个。

如果您想获取conversationEnrolments节点下的整个项目列表,请使用'value'事件并执行以下操作:

    var ref = firebase.database().ref('conversationEnrolments');
    ref.once('value', function (data) {
        data.forEach(snap => {
            console.log(snap);
            console.log(snap.val());
        });
    });

然后,您的代码中存在第二个问题:由于一次()方法是异步的,并且返回一个promise(请参阅doc),您需要等待此承诺已经在能够使用users变量之前已解决,如下所示。查看执行不同console.log()的顺序。

    let users = []

    var ref = firebase.database().ref('conversationEnrolments')
    ref.once('value', function (data) {
        data.forEach(snap => {
            console.log(snap);
            console.log(snap.val());
            users.push(snap.val());
        });
    }).then(() => {
        //Here, the promise has resolved and you get the correct value of the users array
        console.log("users AFTER promise has resolved");
        console.log(users);
    })
    console.log("users BEFORE promise has resolved");
    //Here the console.log prints the value of the array before the promise has resolved and.... it is empty!
    console.log(users);

更新:如何在函数中封装此代码。

    function getUsers() {

        let users = []
        var ref = firebase.database().ref('conversationEnrolments');
        return ref.once('value', function (data) {  //The function returns the result of the promise
            data.forEach(snap => {
                users.push(snap.val());
            });
        }).then(() => {
            return users;  
        })
    }

    //The getUsers() is asynchronous
    //Call it as follows: since it returns a promise, use the result within the then().
    getUsers().then((users) => { console.log(users) });