Angularjs: A service that serves multiple resource / data source URLs?

I have an Angular service / provider that serves json data for my controller that works fine:

angular.module('myApp.services', ['ngResource']). factory("statesProvider", function($resource){ return $resource('../data/states.json', {}, { query: {method: 'GET', params: {}, isArray: false} }); }); 

But I also need to serve json data to one controller from another counties.json file.

Where can I find out how to write a service that serves both files on my controller?

+43
angularjs controller
Jun 18 '13 at 4:52
source share
2 answers

You can update the service to return a hash of resources, and not one:

 angular.module('myApp.services', ['ngResource']). factory("geoProvider", function($resource) { return { states: $resource('../data/states.json', {}, { query: { method: 'GET', params: {}, isArray: false } }), countries: $resource('../data/countries.json', {}, { query: { method: 'GET', params: {}, isArray: false } }) }; }); 

You can use it by adding .query() at the end, your function name, i.e. geoProvider.states.query() and geoProvider.countries.query() and myApp.services should be entered into your controller, then enter the geoProvider service in the controller itself, ok.

+92
Jun 18 '13 at 7:57
source share

I assume that you want to execute some code when both files are loaded. Promises works great for this. I don't think resources return promises, but you can use the $ http service for simple ajax calls.

Here I define one service for two data files and a third service that returns a promise that is executed when both files are downloaded.

 factory('states',function($http) { return $http.get('../data/states.json'); }). factory('countries',function($http) { return $http.get('../data/countries.json'); }). factory('statesAndCountries', function($q, states, countries) { return $q.all([states, countries]); }); 

Then in your controller:

 statesAndCountries.then(function(data) { var stateData = data[0]; var countryData = data[1]; // do stuff with stateData and countryData here }); 
+9
Jun 18 '13 at 5:05
source share



All Articles