在AngularJs资源中可选的url参数

时间:2022-11-26 18:51:38

I have this kind of resource: var Products = $resource('companies/:companyId/products') The problem is, that I would like to get the products of all companies by url companies/products, but using resource and not providing companyId I am getting companies//products. Probably I could use another url, like just /products, but does it mean that I have to have another resource for the same thing?

我有这样的资源:var产品= $resource(‘companies/:companyId/ Products’)问题是,我想通过url公司/产品获得所有公司的产品,但是使用resource而不提供companyId我得到的是company //产品。也许我可以使用另一个url,比如just /products,但这是否意味着我必须有另一个资源来做相同的事情?

In this simple case I could change the url to companies/products/:companyId, but it seems to be quite general case.

在这个简单的例子中,我可以将url更改为公司/产品/:companyId,但它似乎是非常普通的情况。

1 个解决方案

#1


13  

Yes, currently you need to define another $resource.

是的,目前您需要定义另一个$resource。

But you can wrap multiple instances of $resource into a single service if you want...

但是如果您想要,您可以将$resource的多个实例打包到一个服务中。

app.factory('mergedRes', function($resource) {
  var r1 = $resource('/companies/:companyId/products');
      r2 = $resource('/companies/products');

  r1.getAll = r2.query.bind(r2);

  return r1;
});

#1


13  

Yes, currently you need to define another $resource.

是的,目前您需要定义另一个$resource。

But you can wrap multiple instances of $resource into a single service if you want...

但是如果您想要,您可以将$resource的多个实例打包到一个服务中。

app.factory('mergedRes', function($resource) {
  var r1 = $resource('/companies/:companyId/products');
      r2 = $resource('/companies/products');

  r1.getAll = r2.query.bind(r2);

  return r1;
});