Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.JS Fire off two async service calls, then perform action after both have completed

Tags:

angularjs

I'm still wrapping my brain around Angular.JS.

I have two independent $http calls that retrieve data from remote web services. I have an action that I want to fire off after both service calls have been completed.

  1. The first service call will populate the $scope.model
  2. The second service call, modifies data in the $scope.model (it adds some counter properties that are rendered in the view)

Another unique requirement is that eventually the second service call will be called and updated outside the controller with the $scope.model. It's a notification message pump.

I'm guessing I'm going to use promises $q and possibly $service, but I'm not really sure where to start for something like this following some best practices.

I know it doesn't sound like async calls are appropriate here, since my example it could be simplified by doing it syncronously. However, the second service call is a notification updater, so it'll get continually polled to the server (eventually a websocket will be used).

It's a common pattern I'll see in this application.

like image 829
taudep Avatar asked Feb 27 '13 14:02

taudep


1 Answers

You'll want to use $q promises. Specifically $q.all(). All $http methods will return promises. $q.all([promise, promise, promise]).then(doSomething) will wait for all promises to resolve then call doSomething passing an array of the promises results to it.

app.service('myService', ['$http', '$q', function($http, $q) {
   return {
      waitForBoth: function() { 
          return $q.all([
             $http.get('/One/Thing'),
             $http.get('/Other/Thing')
          ]);
      };
   }
}]);

Then call it:

app.controller('MyCtrl', ['$scope', 'myService', function($scope, myService) {
   myService.waitForBoth().then(function (returnValues){
       var from1 = returnValues[0].data;
       var from2 = returnValues[1].data;
       //do something here.
   });
}]);

Here's a demonstration Plunker for you.

like image 61
Ben Lesh Avatar answered Sep 24 '22 23:09

Ben Lesh