This article is about firebase functions that we use for retrieving or writing data into the Firebase realtime-databse.
In some situations, our program is completed before the firebase function could do its work!
It is a common problem for people using the firebase technology. Although if your network is fast enough you might not encounter such problems!
For example, think of a situation where you want to set the roll number of a new student! You would need to fetch the last roll number of the students and then write it back to the database by an increment.
The user clicks on submit button :
- <button type="submit" class="btn btn-success" onclick="setStudentInfo()">Submit</button>reateStudentId() function is called for executio
setStudentInfo() function is called for execution
- function setStudentInfo(studentInfo)
- {
- firebase.database().ref("students/" + studentId).set(studentInfo);
- }
The execution of the function completes even before the database is written with the new value. This happens, because firebase does not provides with any callback methods. I have even tried Promises, but it didn't work. So, the REST API method is better.
REST API using AngularJS. Firebase provides rest api for accessing its database:
- Open Firebase Console
- Go to the realtime-database section
- Copy the link above your database (https://xyz.firebasio.com/)
- Add .json at the end of the link and use it as url (https://xyz.firebasio.com/news.json)
Never leave your database security public after initial development. To use the api in angular,
- angular.module('inFeed', ['ngRoute']).controller('formController', function($scope, $http) {
- $scope.setStudentInfo = function() {
- var studentInfo = { ....
- }
- $http.put("https://xyz.firebasio.com/news" + ".json", studentInfo).then(function mySuccess(response) {
- console.log(response.data + " &status=" + response.status + " &statustext=" + response.statusText);
- console.log("store created");
- }, function myError(response) {
- console.log(response.statusText);
- });
- };
- });
This should do your work!
For detailed information about angularJS http module, go to their documentation.
What is Firebase?
Quoting directly from the Firebase's homepage:
Firebase helps you build better mobile apps and grow your business.
Yes, firebase does helps a lot to build a better mobile app. What's more interesting ? It is free up to a great extent!
- Build apps fast, without managing infrastructure - Easy setup, simple to use!
- Backed by Google, trusted by top apps - Secured, Dependable!
- One console, with products that work together - More than 20 different features!
Learn. Build. Enjoy.