krv
krv

Reputation: 2910

Firebase getting data from angular factory

I have to setup a factory and I want it to return the data that it gets from fire-base. The factory is as such:

.factory('companyFactory', function($firebaseArray) {
var itemsRef = new Firebase("https://somename.firebaseio.com/");
var allNodes=$firebaseArray(itemsRef);

 var myObject={
  getNames: function() {
     itemsRef.once("value", function(snapshot) {
      var nameSnapshot = snapshot.child("companyName");
      var name = nameSnapshot.val();
      return name; //this does not return the data
    });
  }

 } 

return myObject;
});

In my controller I am doing this:

 $scope.companies=companyFactory.getNames();//not working

What should I do to get this working. I want to fetch the data once then serve it up using the factory to different views

Upvotes: 0

Views: 348

Answers (1)

Chandermani
Chandermani

Reputation: 42669

The request itemsRef.once to Firebase is async, so you need to use promise to return names.

var myObject={
  getNames: function() {
     var defer = $q.defer();
     itemsRef.once("value", function(snapshot) {
      var nameSnapshot = snapshot.child("companyName");
      var name = nameSnapshot.val();
      defer.resolve(name); //this does not return the data
    });
    return defer.promise;
  }

And in your calling code you need to use the promise callback pattern to get the data.

companyFactory.getNames().then(function(data) {
  $scope.companies=data;
});

Upvotes: 1

Related Questions