Skip to content Skip to sidebar Skip to footer

Creating A Promise For Accessing Multiple Datapoints From Firebase Using Angular Factory

I have a factory that gets an array of ID's that I use to pull data from firebase. 1 ID pulls 1 piece of data from firebase I want to create a factory that returns a promise that

Solution 1:

You can use $q.all. I simulated an async request using $timeout but the following should give you an idea.

var app = angular.module('app', []);

app.controller('myController', function($scope, myService) {
  myService.getAll([1,2,3,4,5]).then(function(results) {
    $scope.results = results;
  });
});

app.service('myService', function($q, $timeout) {
  this.getAll = function(ids) {
    var promises = [];
    
    ids.forEach(function(id) {
      promises.push(getForId(id));
    });
    
    return $q.all(promises);
  };
  
  function getForId(id) {
    return $timeout(function() {
      return 'Results for ' + id;
    }, Math.random() * 2000);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
  <pre>{{ results | json }}</pre>
</div>

Post a Comment for "Creating A Promise For Accessing Multiple Datapoints From Firebase Using Angular Factory"