The received reply does not align with the set parameter configuration:

Encountering an issue with 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}

Initialization of ng app is 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 } })
});

Within the 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 response from the server:

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

Error is triggered by the above JSON structure

To resolve the error, when sending a simpler JSON without "List", it works fine:

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

Being new to Angular, unsure about the mistake being made.

Answer №1

Instead of using

$scope.Programs = ProgramsResource.query(

Try

$scope.Programs = ProgramsResource.get(

query function assumes the response is an array, while get expects an object. Since you are returning an object, use get.

The default setting for the query function is isArray:true. This flag helps angular to deserialize your response into either an object or an array. Refer to the resource documentation for more information.

Additionally: If you modify the default settings for a query function like in the example below, make sure to include isArray: true to avoid encountering errors. Always add isArray: true when customizing settings for query:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining Mouseover and Click Events in Vue JS

Having four pictures, I want to display a specific component when hovering over them. However, I also need to bind the click event so that clicking on the picture will reveal the component. The challenge is that I am unable to simultaneously bind two event ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

I require the parsing and storage of a list of values from either a JSON or YAML file

To extract specific values from a yaml or json file, the following example demonstrates how to do so. The content below is from a sample yaml file: swagger: '2.0' info: description: >- This is a sample server Petstore server. You can fi ...

During the present module, retrieve the runtime list of all modules that are directly imported (Javascript/Typescript)

Imagine you have a set of modules imported in the current module: import {A1, A2, A3} from "./ModuleA"; import {B1, B2, B3} from "./ModuleB"; import {C1, C2, C3} from "./ModuleC"; function retrieveListOfImportedModules() { // ...

Unraveling JSON Data with jQuery - Exploring Multidimensional Arrays

I'm facing a challenge while trying to parse the response data in json format. Here is the JSON output obtained from an external URL: [ { "id": "1", "qtext": "Do you like this product?", "op": [ { "oid": "1", ...

What is the best way to retrieve variables from child components within a parent component in React?

I'm currently diving into React by working on a form/calculator application. I've come to realize that React follows a unidirectional pattern, and I'm struggling with how to deal with it. My goal is to create a table where users can input i ...

Troubleshooting module not being found with rekuire, requirish, or rfr in resolving relative require problem in nodejs

Looking to steer clear of the complicated relative path problem detailed here by opting for one of the suggested solutions. I've found three similar libraries that could help: rekuire node-rfr aka Require from Root requirish I've experimented ...

Implement a code to apply to an image that is loaded dynamically

I have a situation on a page where an image is loaded via ajax within a wrapping div. I need to execute some code as soon as that image is loaded. Unfortunately, I am unable to modify the ajax call, which means using on('success') directly on the ...

Deleting an item in Vue.js with the removal feature

After deleting items from my list, they remain visible until I manually refresh the page. How can I fix this issue? List <tbody> <tr v-for="school in schools" v-bind:key="school.id"> <td>{{ school.id }}</td> &l ...

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...

Utilize jq to group and tally JSON data

I need to convert the JSON data provided into a CSV format that lists each unique "name" along with the total count of how many times it appears. Given data: [ { "name": "test" }, { "name": "hello" }, ...

What is the importance of using explicit casting in Java when dealing with JSON parsing or processing webservice responses?

Trying to extract and interpret Json response from the Google GeoCoding API using org.JSON within Java. The response stream can be either a JSONObject or JSONArray according to API specifications. Q1: The need to explicitly cast them each time (as shown i ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

Iterating through the parsed JSON data in Ruby

Currently, I am working on iterating through a parsed JSON response retrieved from reddit's API. After conducting some research online, I have come across similar issues faced by others. However, none of the suggested solutions seem to resolve the pr ...

Unable to assign attribute following discovery

Can the attribute of an anchor element that is found using find() be set? I attempted this: $(this).children('a').setAttribute("href","a link"); Although it does locate the anchor element, why am I receiving an error when trying to use setAttr ...

Incorporating external content to make it easily discoverable by Google for optimal SEO performance

I am currently working on a project that involves loading external content onto a customer's site. Our main goal is to provide the customer with a simple inclusion method, such as a one-line link similar to Doubleclick, without requiring any server-si ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

Having Trouble with Finding Visible Divs?

Below is the code snippet I am working with: var len = $(".per:visible").length; $("#add-person").click(function(){ if ($(".persons div:visible").next().is(':hidden')){ $(".persons div:visible").next().slideDown('slow' , ...

What could be the reason that Vue is not evaluating anything when the directive @click is specified as "true && method"?

Consider the following scenario: LandingPage.vue <template> <button @click="handleClick">Click Me</button> </template> <script> export default { methods: { handleClick() { this.$emit("click"); } } }; < ...

Tips on parsing JSON data with Python

I am currently working with a module that provides data in the following format: j = ("{u'auth_user': {u'first_name': u'a', u'last_name': u'b', u'uid': u'x', u'timezone_offset&apos ...