[英]How to make $resource accept array of strings (AngularJS)
我想向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”(请参见下面的代码段),但这也不起作用。
{
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对象,并且不显示意外行为。
(这最初是评论,但它需要格式干净的代码示例。)
我怀疑您的:productIds
模板参数已作为"[object Object]"
填充到模板中。 我只看到了您的模板URL,没有看到实际的构造URL,所以我不确定。
如果您的服务器期望使用:productsIds
模板参数为JSON的URL,例如---
rest/products/productsInfo/["id1","id2","id3"]/{"prop1":true,"prop2":false}
---然后尝试将getProductsInfo
定义编辑为如下形式:
productRestService.getProductsInfo = function (productIds, properties) {
var ProductsInfo = $resource('/rest/products/productsInfo/:productIds/:properties', {
productIds: function () {
return angular.toJson(productIds);
},
properties: function () {
return angular.toJson(properties);
}
});
return ProductsInfo.query();
}
(警告,我没有测试此代码。这只是您的示例的快速编辑。)
这样,您可以确保参数值将转换为服务器期望的JSON(也就是说,如果服务器期望URL中的JSON)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.