Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

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

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

    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 the same controller from another file counties.json.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can update service to return a hash of resources, not a single 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 will be able to use it adding .query() at the end your function name i.e. geoProvider.states.query() and geoProvider.countries.query() and myApp.services has to be injected into your controller, then inject geoProvider service into controller itself as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...