[英]How to specify different URLs for collections vs. single records with ngResource
我正在尝试使用ngResource消耗firebase rest API。 该API使用略有不同的URL来检索集合与单个记录。 例如,我有一个可以访问的集合:
https://angular-resource-test.firebaseIO.com/systems.json
但是,如果要访问单个系统,请使用:
https://angular-resource-test.firebaseIO.com/systems/1.json
如何在资源声明中为此指定基于参数的URL?
通常我会做类似的事情
app.factory('System', ['$resource', function($resource) {
var System = $resource(
'https://angular-resource-test.firebaseIO.com/systems/:id.json',
{id: "@id"},
{update: {method: "PUT"}}
);
return System;
}]);
但这对于集合失败,因为它缺少结尾的.json。 另外,当我指定一个适用于集合的URL时,选择单个行的情况将失败。 有关示例,请参见此jsfiddle:
有两种方法可以在资源中发送HTTP GET。
您的api并不是很安静,因此,您将需要2个资源来执行所需的操作,因为它们使用了不同的URI(请参阅Carl的答案)。 我不知道您是否可以编辑REST服务,但是执行此操作的好方法是: https : //angular-resource-test.firebaseIO.com/systems/用于查询(期望数组) https:// angular -resource-test.firebaseIO.com/systems/:id获取。 (期待一个对象)
通过此服务,您可以使用您的资源:
var System = $resource(
'https://angular-resource-test.firebaseIO.com/systems/:id',
{id: "@id"},
{update: {method: "PUT"}}
);
您可以这样拨打电话:
var systems = System.query({});
var system = System.get({id:1});
您的问题应通过使用isArray:true来解决,以获取查询和获取System和SystemType的方法。 它与如何在服务器端格式化json有关。 有关更多讨论,请参见angular文档。 http://jsfiddle.net/D5E6w/24/
{
update: { method: "PUT" },
query: { method: "GET", isArray: true },
get: { method: "GET", isArray: true }
}
这是一个既有系统集合又有单个记录的工作示例。 注意每个的isArray值。 http://jsfiddle.net/D5E6w/51/
这是我替换整个$ resource URL的解决方案。 我需要这样做,因为我使用的是HAL Rest响应,例如在进行分页时,我想替换整个URL,而不仅仅是替换其中的参数。
app.factory('$rest', ['$resource', 'HALParser', function($resource, HALParser) {
return function($url) {
$url = ($url == null) ? 'http://localhost:8000/:type' : $url;
return $resource($url, {type: ''}, {
update: { method:'PUT' },
get : {
method: 'GET',
transformResponse: [function(data) {
return (new HALParser()).parse(angular.fromJson(data));
}]
}
});
}
}]);
接着,
app.controller('VendorsController', ['$scope', '$rest',
function($scope, $rest) {
$scope.data = $rest().get({type: 'vendors'});
$scope.create = function() {
$rest().save({type: 'vendors'}, {name: $scope.item});
};
$scope.load = function($item) {
console.log($item);
};
$scope.page = function($url) {
$scope.data = $rest($url).get();
};
}]);
我只是将$ resource返回的服务信息包装了一个带有参数URL的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.