環境設定
-
取得金鑰
-
貼到
index.html
- 注意
Firebase SDK
拆分了核心和其他功能- 核心
<script src="https://www.gstatic.com/firebasejs/6.4.2/firebase-app.js"></script>
- 資料庫
<script src="https://www.gstatic.com/firebasejs/6.0.1/firebase-database.js"></script>
- 驗證
<script src="https://www.gstatic.com/firebasejs/6.0.1/firebase-auth.js"></script>
- 核心
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <!-- The core Firebase JS SDK is always required and must be listed first --> <script src="https://www.gstatic.com/firebasejs/6.4.2/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/6.0.1/firebase-database.js"></script> <!-- TODO: Add SDKs for Firebase products that you want to use https://firebase.google.com/docs/web/setup#config-web-app --> <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "AIzaSyB-eXX5WOfITht_Q4XvQm1IDS2M6_HRGqo", authDomain: "node-test-156c2.firebaseapp.com", databaseURL: "https://node-test-156c2.firebaseio.com", projectId: "node-test-156c2", storageBucket: "", messagingSenderId: "839534870273", appId: "1:839534870273:web:cb3b07cf486fc7ea", }; // Initialize Firebase firebase.initializeApp(firebaseConfig); console.log(firebase.database()); // 如有印出 </script> </body> </html>
- 注意
-
如有正確印出
firebase.database()
,即設定完成
設定資料
-
規則
ref
尋找資料庫路徑set
新增資料- 無法寫入陣列,一定是 key value
-
練習 1
firebase .database() .ref() .set("hi");
-
無法寫入可能是權限問題
-
-
練習 2
firebase .database() .ref() .set({ student1: { name: "小白", age: 18, }, student2: { name: "小黑", age: 20, }, }); firebase .database() .ref("student1/name") .set("小黃");
取得資料
-
規則
once
讀取一次資料庫的資料on
即時資料呈現
-
練習 1
firebase .database() .ref() .once("value", function(snapshot) { console.log(snapshot.val()); });
-
練習 2,即時更新
<h1 id="title"></h1> <script> // 省略設定 firebase .... firebase .database() .ref() .set("hi"); firebase .database() .ref() .on("value", function(snapshot) { var title = document.getElementById("title"); title.textContent = snapshot.val(); }); setTimeout(function() { firebase .database() .ref() .set("hello"); }, 3000); </script>
新增資料/移除資料
-
規則
- push 新增
- key 是隨機編號
- remove 移除
- child 子路徑
- push 新增
-
練習 1
var todos = firebase.database().ref("todos"); todos.push({ content: "逛街" }); todos.push({ content: "打東東" });
-
練習 2
var todos = firebase .database() .ref() .child("todos"); // 等價於 // var todos = firebase.database().ref("todos"); // 利用 key 刪除 todos.child("-LnGFwIBpu1Gev5dnhhA").remove();
練習 Todo List
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<h1>待辦事項</h1>
<div>
<input type="text" id="input" />
<button id="button">新增</button>
</div>
<ul id="todos">
<li></li>
</ul>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.4.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.0.1/firebase-database.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyB-eXX5WOfITht_Q4XvQm1IDS2M6_HRGqo",
authDomain: "node-test-156c2.firebaseapp.com",
databaseURL: "https://node-test-156c2.firebaseio.com",
projectId: "node-test-156c2",
storageBucket: "",
messagingSenderId: "839534870273",
appId: "1:839534870273:web:cb3b07cf486fc7ea",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var todosRef = firebase.database().ref("todos");
// 新增待辦事項
var input = document.getElementById("input");
var button = document.getElementById("button");
button.addEventListener("click", function() {
var todo = input.value;
todosRef.push({ content: todo });
input.value = "";
});
var todosDom = document.getElementById("todos");
// 取得所有待辦事項
todosRef.on("value", function(snapshot) {
var todos = snapshot.val();
var todosDomContent = "";
for (var key in todos) {
var todo = todos[key];
todosDomContent += `<li data-key="${key}">${todo.content}</li>`;
}
todosDom.innerHTML = todosDomContent;
});
// 刪除單筆待辦事項
todosDom.addEventListener("click", function(event) {
if (event.target.nodeName == "LI") {
var key = event.target.dataset.key;
todosRef.child(key).remove();
}
});
</script>
</body>
</html>
進階搜尋
-
規則
- orderByChild 排序
- null > false > true > number > string > object
- startAt 多少以上
- endAt 多少以下
- equalTo 等於
- limit 限制筆數
- limitToFirst 從前面
- limitToLast 從後面
- orderByChild 排序
-
練習 1
var peopleRef = firebase.database().ref("people"); peopleRef.set({ tom: { height: 180, weight: 80, }, mike: { height: 170, weight: 100, }, kevin: { height: 175, weight: 60, }, }); peopleRef.orderByChild("height").once("value", function(snapshot) { console.log(snapshot.val()); // 無法取得排序資料 snapshot.forEach((item) => { // 需搭配 forEach 才能取得排序資料 console.log(item.val()); }); });
-
練習 2
var peopleRef = firebase.database().ref("people"); peopleRef.set({ tom: { height: 180, weight: 80, }, mike: { height: 170, weight: 100, }, kevin: { height: 175, weight: 60, }, }); peopleRef .orderByChild("height") .startAt(175) .once("value", function(snapshot) { console.log(snapshot.val()); // 無法取得排序資料 snapshot.forEach((item) => { // 需搭配 forEach 才能取得排序資料 console.log(item.val()); }); });
-
練習 3
var peopleRef = firebase.database().ref("people"); peopleRef.set({ tom: { height: 180, weight: 80, }, mike: { height: 170, weight: 100, }, kevin: { height: 175, weight: 60, }, }); peopleRef .orderByChild("height") .startAt(175) .limitToFirst(1) .once("value", function(snapshot) { console.log(snapshot.val()); // 無法取得排序資料 snapshot.forEach((item) => { // 需搭配 forEach 才能取得排序資料 console.log(item.val()); }); });