Ngresource指定不同的URL获取所有并获得一个

时间:2015-12-10 16:06:26

标签: javascript angularjs json ngresource

我有一个RESTFUL API,其GET网址是

对于所有人:/comersomers.json

单曲:/comersomers/1.json

angular.module('myApp.services', []).factory('Customer', function($resource) {
  return $resource('api/v1/customers/:id.json', { id:'@customers.id' }, {
    update: {
      method: 'PATCH',



    }
    }, {
    stripTrailingSlashes: false
    });
})

任何人都可以告诉我如何将两个获取呼叫网址分开,尝试检查文档,但它们似乎已关闭。

1 个答案:

答案 0 :(得分:1)

你有query收集和get对象,所以像这样:

angular.module('app', ['ngResource'])

.service('Customer', function($resource){
    return $resource('api/v1/customers/:id.json');
 })

.controller('ctrl', function(Customer){
    Customer.query().$promise.then(function success(result){
        console.log(result);
    }, function fail(reason){
        console.log(reason);
    }); 

    Customer.get({id: 1}).$promise.then(function success(result){
        console.log(result);
    }, function fail(reason){
        console.log(reason);
    });
})

;

您还可以指定方法是否为数组,请查看默认的$resource方法:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

你可以在这里查看: http://jsbin.com/cesifo/3/edit?html,js,output

和$ resource docs: https://code.angularjs.org/1.4.8/docs/api/ngResource/service/$resource