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

Waj*_*man 12 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
]
Run Code Online (Sandbox Code Playgroud)

错误:-

[$ 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>
Run Code Online (Sandbox Code Playgroud)

ItemsService.js

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

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);
            }
        );  
});
Run Code Online (Sandbox Code Playgroud)

ric*_*i90 16

文档:

行动是阵营

isArray – {boolean=} – If true then the returned object for this action is an array, see returns section.

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

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

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

从你的代码

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

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


Vic*_*box 7

在我的例子中,API服务器返回一个被视为字符串的HTML页面(错误页面),而不是正确的JSON响应,它将是一个javascript对象.

作为旁注,javascript错误和堆栈跟踪确实是一些东西.