javascript - 如何修复预期响应以包含数组但得到一个对象ANgular js

标签 javascript angularjs

我是新手,很难在调用服务后使用资源模块得到这个错误。 任何人都可以在我出错的地方修改我的代码错误,或者只是修改需要纠正的部分,谢谢。

数据格式:-

[
    brands: Array[1]
    0: Object
    __v: 0
    _id: "5251a4a34f232fc3902"
    account_id: "525072320e32971b"
    name: "Fruits"
    __proto__: Object
    1: Object
    length: 2

    categories: Array[1]
        0: Object
        __v: 0
        _id: "5251a4a34f2323fc3902"
        account_id: "5250723230e32971b"
        name: "Fruits"
        __proto__: Object
        1: Object
        length: 2
]

错误:-

[$resource:badcfg] 资源配置错误。预期响应包含一个数组但得到一个对象

itmsFormView.html

<select class="form-control" ng-model="item.brand_id" id="itemBrand" >
    <option value="">Select Brand</option>
    <option ng-repeat="brand in brands" value="{{brand.brand_id}}">{{brand.name}}  </option>
</select>



 <select class="form-control" ng-model="item.category_id" id="itemCategory">           

<option value="">Select Category</option>
       <option ng-repeat="category in categories" value="{{category.brand_id}}">{{category.name}}</option>
    </select>

ItemsService.js

app.factory('itemService', function ($resource) {
    return {
        getCategoryAndBrand   :  $resource("/user/categories_brands" ,{},{ TypeGetCategoryAndBrand:{method: 'get', isArray:true}})
    };
});

ItemsController.js

app.controller('itemsFormController', function ($rootScope, $scope, itemService, $location, $cookies, $routeParams) {
        itemService.getCategoryAndBrand.TypeGetCategoryAndBrand({}, function(response){
                console.log(response);

            },function(errorResponse){
                console.log(errorResponse);
            }
        );  
});

最佳答案

来自documentation :

Action 是数组

isArray – {boolean=} – 如果为真,则此操作返回的对象是一个数组,请参阅返回部分。

根据您的代码 isArray = true。将其设置为 false,您就可以使用对象而不是数组。

app.factory('itemService', function ($resource) {
return {
        getCategoryAndBrand   :  $resource("/user/categories_brands" ,{},{ TypeGetCategoryAndBrand:{method: 'get', isArray:true}})
    };
});

它期望您将参数作为数组而不是对象传递

来自您的代码

$resource("/user/categories_brands",{},{ TypeGetCategoryAndBrand:{method: 'get', isArray:true}})

如果要相信文档而不是你得到的错误,我会尝试以数组的形式而不是对象的形式传递它,看看你是否得到相同的响应。

关于javascript - 如何修复预期响应以包含数组但得到一个对象ANgular js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20020087/

相关文章:

javascript - 将每个 div 附加到 Javascript 变量

javascript - setInterval 随着时间的推移变慢

javascript - 如何使用 angularjs 创建 ListView ?

javascript - 单击 UI 网格上的链接时的 Bootstrap Modal

javascript - Angular $scope 变量自行更新

javascript - 使用 E4X,我可以关闭缩进吗?

java - 如何获取经过哈希处理的数据的真实值(value)?

javascript - 使用 await 而不是 Promises 的正确方法是什么?

javascript - Adobe Creative SDK Web 加载后显示小图像

angularjs - 我如何在 Angular 中模块化 polyfill?