如何使 $resource 接受字符串数组 (AngularJS)

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 对象的默认行为是在使用 "query" 时它需要一个对象数组。

我怎样才能让我的 $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,所以我不能确定。

如果您的服务器期望 URL,其中 :productsIds 模板参数为 JSON,例如 ---

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,即是).