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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With