AngularFire - $ firebaseArray can $ add, but not read

I feel like I am missing something very simple. Here is part of my service:

angular.module('fire')
  .constant('FIREBASE_URI', 'https://___.firebaseio.com/')

  .factory('syncArraySvc', function(FIREBASE_URI, $firebaseArray) {

    var buildingsUri = FIREBASE_URI + "buildings";
    var buildings = $firebaseArray(new Firebase(buildingsUri));
    console.log(buildings);

    var getBuildings = function() {
      return buildings;
    };
    var addBuilding = function(item) {
      buildings.$add(item);
    };
    return {
      getBuildings: getBuildings,
      addBuilding: addBuilding
    };
  });

      

The .log console in the middle of this just returns an empty array. If I try to call the function syncArraySvc.getBuildings()

from another controller, I also get an empty array. One way or another, it $add(item)

works like syncArraySvc.addBuilding(item)

. What am I missing?

+1


source to share


3 answers


Other answers helped me to point in the right direction.

There is some sample code in the API documentation that doesn't seem to need the data to be wrapped in a promise:

var list = $firebaseArray(new Firebase(URL));
$scope.list = list;

      



However, he points out that you can use a promise $loaded

to notify when data is loaded. This is how I got it to work in my project:

syncArraySvc.getBuildings().$loaded(function(data) {
  $scope.buildings = data;
});

      

I tried to reproduce this in a new project and worked consistently without a shell $loaded

as shown in the first example. It makes sense to me that a wrapper would be required $loaded

. I don't understand how it can work in the first example without it.

+1


source


If you look at $ add $firebaseArray

, it creates a new element and adds it to $firebaseArray

, as if we have buildings

. But once you add an item to $ firebaseArray, it is not instantly added. It is added when the $ add promise appears.

I think you are doing the right thing, you only need a method call syncArraySvc.addBuilding(item)

for the promise to succeed $add

.

To do this approach you need to return a promise from a service method like



var addBuilding = function(item) {
  return buildings.$add(item);
};

      

And then the caller function will take that promise and solve it, it will call the method syncArraySvc.addBuilding(item)

that has confidence that the elements are added to the array buildings

.

syncArraySvc.addBuilding({foo: "bar"}).then(function(addedItem){
    console.log(addedItem);
    console.log(syncArraySvc.addBuilding(item)); //this will show you updated list
})

      

+2


source


Try using the $ timeout service inside the getBuildings function, or rather when you call it. It will probably take some time before the data is returned.

0


source







All Articles