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

Converting JSON Responses in Android: A Guide

After creating my JSON response model class, here is how it looks: data class MyModelClass( val one: String, val two: String, val three: String, val four: Int, val tempCurrentCharge: List<CurrentCharge>, ...

Transmitting information to a web service through POST method

Recently, I was given an example on how to connect to a specific web server. This example includes a basic form with two input fields: Upon submitting the form with both the token and the JSON data, it returns a true response. Below is the HTML code: & ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...

JavaScript - An unexpected error occurred: Syntax error, unrecognized expression: [href=#contact] (WordPress)

I am currently working on a feature that involves adding a class to a specific menu item when a certain section is in view. However, I encountered an error that reads: Uncaught Error: Syntax error, unrecognised expression: [href=#contact] Your help would ...

How come lazy loading isn't functioning in my React project?

Check out my project: link. This project includes routers and lazy-loaded components for each page. Here's a brief example of a router component: export const RoutersComponent = () => { return ( <HashRouter basename={'/'}> ...

"Troubleshooting: Angular ng-show not triggering correctly upon first loading of the

Utilizing Angular's ng-show directive to adjust the display of questions in a quiz and show a result upon completion, everything is functioning as intended except for the initial question. Upon loading the quiz, $scope.image is initialized as false. S ...

Displaying and Concealing Divisions

My journey to showing/hiding divs began with piecing together a series of questions: $(document).ready(function(){ $('.box').hide(); $('#categories').onMouseOver(function() { $('.box').hide(); $('#div' + ...

Tips on using jQuery to horizontally align an element in the viewport

Although this question has been raised before, my situation is rather unique. I am currently constructing an iframe for future integration into a slideshow component on the website. The challenge lies in the fact that I have a dynamically sized flexbox th ...

Java Cookie Parsing Techniques

Is there a current open source Java library that can handle browser cookies in compliance with the latest RFC 6265 standard, while still being compatible with older standards like RFC 2109 and RFC 2965 that have been outdated by RFC 6265? Past discussions ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: Take a look at my file structure: I considered using route groups, but that approach disabled wrapping in the contac ...

Is there a guarantee that XHR requests made within a click handler of an anchor tag will always be sent?

I'm trying to find information on whether an XHR request triggered in an anchor tag's click event handler is guaranteed to be sent. Despite my attempts at searching, I can't seem to locate a definitive answer. The specific question I have i ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Using Next.js Link prefetch feature can lead to unexpected 404 errors on a production website

I'm currently working on a Next.JS blog project where I have created a page to showcase all of my articles. When I render the component, it appears like this: <div> {articles.map((article, index) => { const path = `/magazine/${ar ...

The event on the full calendar is stuck in place and will not budge

function moveEvent(event, delta, revertFunc) { console.log(event.title + " has been moved to " + event.start.format()); var page = '../include/UpdateCalendarEvent.php'; $("#dialog") .data('start', event.start.format ...

Disappearing input field in DateTimePicker Bootstrap when blurred

Currently, I am utilizing the Bootstrap DateTimePicker plugin to enable users to select a specific date and time. The plugin functions well with one minor issue - whenever the user clicks outside or loses focus on the calendar box, both the box itself and ...

Struggling to successfully submit data from an API to the project's endpoint, encountering Error 405 method rejection

I'm working on integrating data from the openweathermap API into my project's endpoint to update the User interface. Everything seems to be functioning correctly, except for when I attempt to post the data to the endpoint. What am I overlooking h ...

Create a rectangle when the mouse is pressed down

Creating a zoomable and pannable canvas in Fabric.js was easy, but now I am facing an issue with accurately drawing a rectangle on each mousedown event. The problem arises when the canvas is transformed from its original state, making the coordinates inacc ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Utilize AngularJS to bind keys to arrays

Hey there, I have an array that looks like this: $scope.Selectedgroups =[183,184,24] I want to convert it to the format shown below: [{groupId:183},{groupId:184},{groupId:24}]; I've been trying to convert it using a for loop: var groups=[] ...