首页 > 解决方案 > 如何从 web 中的 firebase 实时数据库中获取数据?

问题描述

我创建了应用程序,安装了 CLI,将脚本添加到 index.html。然后我在实时数据库中添加了记录 {number: 1},登录并在项目文件夹中初始化了 firebase。

实时数据库

这是我的 index.html

<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js"></script>



<!-- TODO: Add SDKs for Firebase products that you want to use
       https://firebase.google.com/docs/web/setup#available-libraries -->
  <script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-database.js"></script>



<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
      ***config***
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    const db = firebase.database();
    console.log(db);
  </script>

为什么我会得到这样的数据?为什么不 {number: 1}?

const db = firebase.database()

标签: javascriptfirebasefirebase-realtime-database

解决方案


// Get a reference to the database service
var database = firebase.database();

// This is reference to tha database, to fetch data from database use below code:

var starCountRef = firebase.database().ref('posts');
// Add ref of child if any
starCountRef.on('value', function(snapshot) {
    console.log(snapshot.val());
});

参考:https ://firebase.google.com/docs/database/web/read-and-write

使用 val() 函数获取 json 格式的数据


推荐阅读