Angularjs: a Service that serves multiple $resource urls / data sources?

后端 未结 2 1445
情深已故
情深已故 2020-11-30 19:05

I have an Angular service/provider that serves json data to my controller which works great:

    angular.module(\'myApp.services\', [\'ngResource\']).
               


        
2条回答
  •  时光取名叫无心
    2020-11-30 19:21

    I'm assuming you want to execute some code when both files have loaded. Promises work really well 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 each for the two data files, and a third service that returns a promise that gets fulfilled when both files are done loading.

    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
    });
    

提交回复
热议问题