Saurabh Palatkar Saurabh Palatkar - 5 months ago 42
JSON Question

Response does not match configured parameter:

I am getting following error in 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}


I initialized the ng app as follows:

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


The service:

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


In my controller:

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 I am sending from the server in respons:

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


The angular $response throws error for above json

But if I do not send "List" array within json and send simple json as follows, everything works fine then:

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


I am new to angular and don't know what exactly I am doing wrong.

Answer

Instead of doing

$scope.Programs = ProgramsResource.query(

Use

$scope.Programs = ProgramsResource.get(

query function expects the response to be an array, where as get expects a object. Since you are returning object use get.

The default setting for query function is isArray:true. This flag helps angular to de-serialize your response into either object or array. See resource documentation.

Also note: When you change default settings for a query function like the following, you will encounter this error if you do not define isArray as true. So always add isArray: true when you change the default settings for query:

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