Google Cloud + Firebase 讲解
Firebase 是一個后端服務,讓開發者能快速部署應用程序。Firebase的一個最終要的功能是提供一個實時的數據庫。隨著現代web和移動端的程序轉移到客戶端,后端服務器習慣提供Model, View, and Controller 功能。這次的博客就講解如何部署一個聊天應用程序。
步驟一:創建一個Google Cloud Project
步驟二:在firebase的頁面加入剛剛創建好的Google Cloud Project
Firebase 的 console: 點擊這里
添加好Google Cloud Project 之后,點擊Continue:
步驟三:應用程序的建立
許多網頁的應用程序都需要后臺來支持。Firebase支持mobile platforms and web。但是,這次主要講解網頁的應用程序。
步驟四:創建授權登錄:
出于安全考慮,Firebase將對其資源的訪問限制在特定的域。會在Cloud Shell 測試這次的應用程序。為了能訪問,需要將它添加到授權域列表中。
步驟五:數據庫的建立
步驟六:storage 的建立
Firebase自動創建好storage。
步驟七:CLI的建立
在Cloud Shell 里寫入以下的命令:
步驟八:測試應用程序
firebase serve --only hosting
步驟九:在代碼里添加authentication
在main.js文件里添加這幾段代碼:
步驟十:更新UI
當用戶改變authentication state,我們就得更新UI.
加上這段代碼
// Listen to auth state changes.firebase.auth().onAuthStateChanged(authStateObserver);獲取用戶的頭像:
return firebase.auth().currentUser.photoURL || '/images/profile_placeholder.png';獲取用戶的名字:
return firebase.auth().currentUser.displayName;用戶沒有登錄就發送消息,程序返回錯誤信息
return !!firebase.auth().currentUser;步驟十一:測試程序授權
運行命令:
當用戶沒有授權登錄,就發送消息,就會出現這個提示:
步驟十二:實現消息發送
// Add a new message entry to the database. return firebase.firestore().collection('messages').add({name: getUserName(),text: messageText,profilePicUrl: getProfilePicUrl(),timestamp: firebase.firestore.FieldValue.serverTimestamp()}).catch(function(error) {console.error('Error writing new message to database', error);}); // Create the query to load the last 12 messages and listen for new ones.var query = firebase.firestore().collection('messages').orderBy('timestamp', 'desc').limit(12);// Start listening to the query.query.onSnapshot(function(snapshot) {snapshot.docChanges().forEach(function(change) {if (change.type === 'removed') {deleteMessage(change.doc.id);} else {var message = change.doc.data();displayMessage(change.doc.id, message.timestamp, message.name,message.text, message.profilePicUrl, message.imageUrl);}});});步驟十三:測試發送信息
運行命令:
回到Firebase, 就可以看到信息已經存到數據庫里
步驟十四:手動添加信息
應用程序就能立即顯示最新的信息:
步驟十五:添加圖像信息
firebase.firestore().collection('messages').add({name: getUserName(),imageUrl: LOADING_IMAGE_URL,profilePicUrl: getProfilePicUrl(),timestamp: firebase.firestore.FieldValue.serverTimestamp()}).then(function(messageRef) {var filePath = firebase.auth().currentUser.uid + '/' + messageRef.id + '/' + file.name;return firebase.storage().ref(filePath).put(file).then(function(fileSnapshot) {return fileSnapshot.ref.getDownloadURL().then((url) => {return messageRef.update({imageUrl: url,storageUri: fileSnapshot.metadata.fullPath});});});}).catch(function(error) {console.error('There was an error uploading a file to Cloud Storage:', error);});步驟十六:測試圖片信息
數據庫里很快更新:
步驟十七:Deploy application
firebase deploy --except functions
點擊URL, 進入程序:
步驟十八:刪除應用程序
點擊“Project settings”
這樣連在Google Cloud Console里的Project也都刪除了。
既然已經看到這了,就麻煩點個贊或者關注或者留言再走唄~~
謝謝~ ~
總結
以上是生活随笔為你收集整理的Google Cloud + Firebase 讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java short转byte_java
- 下一篇: 【物联网+GIS】让传感器数据在三维地图