【发布时间】:2015-02-19 02:19:25
【问题描述】:
我想向查询参数包含字符串数组的 REST 服务发出请求:
productRestService.getProductsInfo(productIdsArray,"id,name,rating").$promise.
then(function(productData) { // success: Produktdaten auslesen
updateProductList(productData);
}, function (error) {
console.log("Status: " + error.status);
});
资源服务如下:
productRestService.getProductsInfo = function(productIds, properties) {
console.log('productRestService.getProductsInfo(): productIds' + productIds);
var productInfoResourceData;
var ProductInfoResource = $resource('/rest/products/productsInfo/:productIds/:properties',
{
productIds:'@productIds',
properties:'@properties'
}
);
productInfoResourceData = ProductInfoResource.query(
{
productIds: productIds,
properties: properties
}
);
return productInfoResourceData;
}
调用服务会导致 404 错误,因为 $resource 对象的默认行为是在使用“查询”时它需要一个对象数组。
我怎样才能让我的 $resoure-service 接受一个字符串数组?我尝试使用“transformRequest”(参见下面的 sn-p),但这也不起作用。
{
query: {
method: 'GET',
isArray: true,
transformResponse: function (data, headers) {
var tranformed = [];
[].forEach.call(eval(data), function (d) {
tranformed.push({ name: d });
});
return tranformed;
}
}
}
REST 服务 productService.getProductsInfo 函数中的 console.log 显示了服务接收到的正确数据:
["212999cc-063b-4ae8-99b5-61a0af39040d","17e42a28-b945-4d5f-bab1-719b3a897fd0","9307df3e-6e7a-4bed-9fec-a9d925ea7dc0"]
该 URL 与其他 REST-URLS 是正确的,应该是这样的(并相应地连接到域):
'/rest/products/productsInfo/:productIds/:properties'
编辑: productService 中的其他函数按顺序响应,它们不使用数组而是使用 JSON 对象,并且不会显示意外行为。
【问题讨论】:
-
困惑;我想 404 是由于构造了一个无效的请求 URL 而导致的——与响应无关(我想 transformResponse 甚至从未被调用过)。您能否提供正在构建的 URL 以及您希望 URL 的外观?
-
我用 cmets 和您请求的 URL 编辑了我的问题。将请求命令中的参数“productIdsArray”类型从数组更改为 JSON(使用 JSON.parse)可解决 404 错误,但我不查询任何数据。
-
您提供的是 URL 模板,而不是 URL。就像@Daniel 提到的那样,您还应该提供一个手动构建的 URL 来显示您希望 URL(而不是模板)的外观,更重要的是,服务器期望它的外观。
标签: arrays angularjs angular-resource