Akshay Bist Akshay Bist - 5 months ago 146
AngularJS Question

Waiting for response from firebase in angularJS

I am new to firebase and I am using new console to simply demonstrate saving, retrieving data from firebase real time database. On retrieving the data, I am connecting it to a model to show it on the screen in list format. But the screen doesn't show anything. I want to use promise to wait until I get the data from the firebase database.

app.factory('Authentication', ['$rootScope', function($rootScope) {
return {
getUsers: function() {
firebase.database().ref('/userInfo').on('value', function (snapshot) {
return snapshot.val();
});
}
}
}


How do I use promise to wait until the data is fetched.

app.controller('myController', function($scope, $rootScope, Authentication) {
$scope.userData = Authentication.getUsers();
}

Answer

First you should install q or download and add the script

1) npm install q --save

2) add this to your app module like adding 'q'

3) add q to your factory and use deffer

app.factory('Authentication', ['$rootScope','q', function($rootScope, q) {
return {
     getUsers: function() {
        var defer = q.defer();
        firebase.database().ref('/userInfo').on('value', function (snapshot) { //assuming you get snapshot value from the db
           defer.resolve(snapshot.val());
           //return snapshot.val();
        });
     return defer.promise;
     }
   }
}

4) then add then to your function

app.controller('myController', function($scope, $rootScope, Authentication) {
   Authentication.getUsers().then(function(snap){
       $scope.userData = snap;
   });
}

you can also add defer .reject to return err and you catch it in other function in your code

for example

app.factory('Authentication', ['$rootScope','q', function($rootScope, q) {
return {
     getUsers: function() {
        var defer = q.defer();
        firebase.database().ref('/userInfo').on('value', function (snapshot) {
           if(!snapshot.val()){
                defer.reject('err no data');
           }else{
                defer.resolve(snapshot.val());
                //return snapshot.val();
           }
        });
     return defer.promise;
     }
   }
} 

and here you do

app.controller('myController', function($scope, $rootScope, Authentication) {
   Authentication.getUsers().then(function(snap){
       $scope.userData = snap;
   }, function(err){
       //do something with the error
   });
}

hope it helped