Reputation: 5000
I want my controller to be able to fetch a list of indicators from an API via a service:
Controller.js
dataService.getIndicators( ["a", "b", "c"] )
DataService.js
this.cachedIndicators = {};
var baseURL = "www.myapi.com/jsonp/indicator/";
this.getIndicators = function(indicators){
//for each indicator not in cache, retrieve it using $http.jsonp()
//when done, indicate that data
}
Can I make use of AngularJS caching and promises here? (a sample implementation would be much welcome.)
Upvotes: 0
Views: 177
Reputation: 789
In case every indicator has its own resource and you need to make multiple requests and want to wait until all requests are done you use the $q.all(..) method which returns a single promise wrapping multiple promises.
for example:
this.getIndicators = $q.all([
$http.jsonp(url1, { cache: true }).then( .. process individual result here ..),
$http.jsonp(url2, { cache: true })
])
Upvotes: 1
Reputation: 2599
Sure you can. In your service, return the promise which is the result of the $http.jsonp() call...
this.cachedIndicators = {};
var baseURL = "www.myapi.com/jsonp/indicator/";
this.getIndicators = function(indicators){
return $http.jsonp(baseURL, { cache: true });
}
...then modify your controller to handle the result of the promise...
dataService.getIndicators( ["a", "b", "c"] ).then(function(data){
// do stuff with the returned data
});
Upvotes: 0