响应与配置的参数不匹配:

时间:2014-09-29 05:21:23

标签: javascript json angularjs

我在angular $ resource中遇到以下错误: error description

Error: error:badcfg
Response does not match configured parameter:
Error in resource configuration for action `array`. Expected response to contain an object but got an {2}

我按如下方式初始化了ng app:

var appRoot = angular.module('smapp', ['ngRoute', 'ui.bootstrap', 'ngResource']);

服务:

appRoot.factory('ProgramsResource', function ($resource) {
    return $resource('Home/Program', {}, { Program: { method: 'get', isArray: false } })
});

在我的控制器中:

appRoot.controller('ProgramCtrl', function ($scope, ProgramsResource) {
    $scope.searchPrograms = function () {
        $scope.Programs = ProgramsResource.query(
            {
                TotalItems: $scope.TotalItems,
                ItemsPerPage: $scope.ItemsPerPage,
                PageNo: $scope.CurrentPage
            });
    };


    $scope.TotalItems = 175;
    $scope.ItemsPerPage = 20;
    $scope.CurrentPage = 1;
    $scope.searchPrograms();
});

Json我正在从服务器发送响应:

{"TotalItems":175,"ItemsPerPage":20,"PageNo":5,"List":[{"Code":"MATH2014","Name":"Name1","Tags":"Tag1,Tag2"},{"Code":"MATH2015","Name":"Name2","Tags":"Tag1,Tag2"}]}

角度$响应抛出上面的json错误

但如果我不发送" List" json中的数组并按如下方式发送简单的json,一切正常:

[{"TotalItems":0,"ItemsPerPage":0,"PageNo":0},{"TotalItems":0,"ItemsPerPage":0,"PageNo":0}}]

我是棱角分明的新人,不知道我到底做错了什么。

1 个答案:

答案 0 :(得分:7)

而不是做

$scope.Programs = ProgramsResource.query(

使用

$scope.Programs = ProgramsResource.get(

query函数期望响应是一个数组,而get期望一个对象。由于您要返回对象使用get

查询功能的默认设置为isArray:true。此标志有助于角度将您的响应反序列化为对象或数组。请参阅resource documentation

另请注意: 当您更改查询功能的默认设置时,如果未将isArray定义为true,则会遇到此错误。因此,在更改isArray: true的默认设置时,请务必添加query

var res = $resource('/api/userinfoes/:Id', { Id: "@Id" },
            {
                'query':  {
                        method:'GET',
                        headers: {
                             'Authorization': 'Bearer ' + token
                        },
                        isArray:true}
            });