Angularjs:服务多个 $resource url/数据源的服务? [英] Angularjs: a Service that serves multiple $resource urls / data sources?

查看:24
本文介绍了Angularjs:服务多个 $resource url/数据源的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular 服务/提供程序,它向我的控制器提供 json 数据,效果很好:

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

但是我还需要从另一个文件 counties.json 向同一个控制器提供 json 数据.

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?

推荐答案

您可以更新服务以返回资源的哈希值,而不是单个资源:

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

您将能够使用它在您的函数名称的末尾添加 .query(),即 geoProvider.states.query()geoProvider.countries.query()myApp.services 必须注入控制器,然后将 geoProvider 服务注入控制器本身.

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.

这篇关于Angularjs:服务多个 $resource url/数据源的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆