AngularJS REST JSON data filter: Error in configuration. The response does not meet the specified parameter

I've been attempting to utilize a routeparam to filter the results of a REST call, but unfortunately I'm encountering issues and receiving the following error message:

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

The specific value I'm trying to retrieve is based on the articlecategoryid. When I test my URL using a browser tool like Postman, it works perfectly fine. An example URL that returns the desired results filtered by articlecategoryid is as follows:

https://myrestcall.net/tables/articles/?$filter=(articlecategoryid eq 1)

However, when implementing this in Angular, it doesn't seem to work and instead throws an error.

Below is a snippet of the sample REST data obtained from this call:

[
{
    "id": "66D5069C-DC67-46FC-8A51-1F15A94216D4",
    "articletitle": "artilce1",
    "articlecategoryid": 1,
    "articlesummary": "article 1 summary. "
},
   {
    "id": "66D5069C-DC67-46FC-8A51-1F15A94216D5",
    "articletitle": "artilce2",
    "articlecategoryid": 1,
    "articlesummary": "article 2 summary. "
}, 
{
    "id": "66D5069C-DC67-46FC-8A51-1F15A94216D6",
    "articletitle": "artilce3",
    "articlecategoryid": 1,
    "articlesummary": "article 3 summary. "
},   
]

Here's how my App setup looks like:

var pfcModule = angular.module('pfcModule', [
'ngRoute',
'ui.bootstrap',
'auth0',
'angular-storage',
'angular-jwt',
'pfcServices',
'pfcControllers']);

pfcModule.config([
... (content retained for brevity) ...
}])

.run(function ($rootScope, auth, store, jwtHelper, $location) {
... (content retained for brevity) ...
});

This section details my service:

     var pfcServices = angular.module('pfcServices', ['ngResource'])


pfcServices.factory('pfcArticleCategories', ['$resource', function ($resource) {
    return $resource('https://myrestcall.net/tables/articles/?$filter=(articlecategoryid eq :articlecategoryID)', { articlecategoryID: '@articlecategoryid' },
    {
        'update': { method: 'PATCH' }
    }
    );
}]);

And here's my controller:

 var pfcControllers = angular.module('pfcControllers', ['auth0']);

pfcControllers.controller('pfcCategoriesCtrl', ['$scope', '$routeParams', 'pfcArticleCategories', function ($scope, $routeParams, pfcArticleCategories) {
... (content retained for brevity) ...
}]);

To display the REST data on the page (categories.html), the code would look something like this:

div class="row">
<div class="col-md-4">
    <h2>Heading</h2>
    Sort By: <select ng-model="articleSortOrder">
        <option value="+id">ID</option>
        <option value="+articletitle">Article Title</option>
        <option value="+articlecategoryid">Article Category</option>
    </select>
    <table class="table table-striped">
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>Category ID</th>
        </tr>
        <tr ng-repeat="articles in category | orderBy:articleSortOrder">
            <td>{{articles.id}}</td>
            <td>{{articles.articletitle}}</td>
            <td>{{articles.articlecategoryid}}</td>
        </tr>
    </table>
</div>

To filter the data based on routeparam, you can use the following links in your page (home.html):

<a href="#categories/1">Article 1 Category</a>
<a href="#categories/2">Article 2 Category</a>

UPDATE: While other REST calls are functional, including those with a routeparam like , the problematic aspect appears to be related to the ?$filter= functionality in the failing call. Are there similar experiences with passing values into a REST call where the variable isn't directly after a / such as in /:articleID?

Answer №1

To ensure that your pfcServices factory is able to handle JSON arrays, make sure you include isArray:true in the 'update': { method: 'PATCH' } method definition.

var pfcServices = angular.module('pfcServices', ['ngResource'])
pfcServices.factory('pfcArticleCategories', ['$resource', function ($resource) {
        return $resource('https://myrestcall.net/tables/articles/?$filter=(articlecategoryid eq :articlecategoryID)', { articlecategoryID: '@articlecategoryid' },
        {
            'update': { method: 'PATCH', isArray:true }
        }
        );
    }]);

isArray – {boolean=} – Make sure to set this to true if the returned object from the action is an array (see returns section).

For more information, refer to the documentation here

Answer №2

Figured it out! The problem was with the controller using a 'Get' method. While 'Get' is suitable for fetching something by id (e.g., ), in this case, I needed to utilize the 'query' command due to its implicit isArray:true behavior (refer to the Angular Resource Documentation where it specifies 'query': {method:'GET', isArray:true}).

By switching my controller code from:

pfcControllers.controller('pfcCategoriesCtrl', ['$scope', '$routeParams', 'pfcArticleCategories', function ($scope, $routeParams, pfcArticleCategories) {
$scope.category = pfcArticleCategories.get({ articlecategoryID: $routeParams.articlecategoryID });
}]);

To:

pfcControllers.controller('pfcCategoriesCtrl', ['$scope', '$routeParams', 'pfcArticleCategories', function ($scope, $routeParams, pfcArticleCategories) {
$scope.category = pfcArticleCategories.query({ articlecategoryID: $routeParams.articlecategoryID });
}]);

The issue was successfully resolved.

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

Upon utilizing AngularFire, the $createUserWithEmailAndPassword function successfully creates a new user; however, it fails to return a promise

Recently, I've been in the process of transitioning an existing project to Firebase 3/AngularFire 2 from a previous Firebase.com setup. This is my first time working with these technologies. My query revolves around using the $createUserWithEmailAndP ...

div value causing erratic behavior in cycling process

Instead of following the normal balance calculation (1000-950), something odd happens and the balance goes from 1000 to 0 with the while loop. I never intended for the refBalance to drop below 0. (numDebit2() returns 50) <div class="elemen ...

Navigating through the concept of passing objects by reference in child components of Angular 2+

Understanding that TypeScript uses object passing by reference can be challenging, especially when dealing with deep copy issues. This becomes particularly cumbersome when working within a theme. I recently encountered an issue with a component containing ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Exploring the capabilities of jQuery by creating custom functions utilizing the .data method and HTML5 data

My goal is to dynamically add a new "app" to my "AppList" when a button is clicked. Javascript Solution: $(".appCreate" ).click(createNewApp); function createNewApp() { var facebookTemplate = $("#facebook-template").html(); var appName = $(this ...

Is it possible to create a form inside a tooltip?

Looking to incorporate a jQuery feature into a form where a simple yes or no question appears upon hovering over it. However, encountering issues getting jQuery to recognize the dynamically created tooltip and submit alert function not working ("$('#w ...

Trigger an Ajax request upon user confirmation, which will only be prompted based on the result of a previous Ajax call

Currently, I am facing a challenging issue surrounding asynchronous calls: A specific JQuery function is triggered on user click. This function then requests a PHP file to check if the user input overlaps with existing information in the database. If an o ...

Testing the JSON request parameters in Apiary

Is there a way to perform JSON request testing with parameters in Apiary? At the moment, I have an API set up with a JSON request containing a few parameters specified using the + Parameters tag. However, this setup is currently generating warnings becaus ...

Adding up whole numbers from a string - JavaScript

JavaScript is still very new to me and I'm facing a challenge: I have an array containing three phone numbers, and I need to calculate the sum of the digits in each phone number string. I want to find and return the phone number with the highest ...

Managing User Sessions in Meteor

Is there a way to dynamically retrieve and set the pageTitle for my Meteor app using jQuery or any other method? I've attempted to achieve this by creating a session when a specific div class is present on the page, but it doesn't seem to be work ...

Differences Between Using WebDriver click() and JavaScript click()

The Scenario: Within the realms of StackOverflow, instances have been observed wherein users encounter difficulties clicking on an element through selenium WebDriver's "click" command. As a solution, they resort to using a JavaScript click by executi ...

What could be causing the malfunction of the .setAttribute() and .removeAttribute functions in my JavaScript program?

Below is a flashcard game I have developed: Once a user enters the correct answer in the text box, "Correct!" is expected to be displayed in bold green font. The CSS attributes are then supposed to be removed shortly after. Here is the HTML code for the i ...

Converting JSON to CSV using Node.js

Looking to convert JSON data to a CSV file in Node.js? Wondering if there are any predefined modules for this task? P.S. Additionally, interested in incorporating formatting such as including headers like "MONTHLY REPORT" and row colors? ...

The Vue template syntax utilizes double curly braces for incrementing values within must

Embarked on learning Vue.js recently and I am intrigued by the unusual behavior in my simple code. I cannot seem to figure out what is going wrong. I am attempting to increment a counter inside mustache syntax, but something strange is happening with this ...

The function Angular.isArray(data) will evaluate to false when checking if the data is

Using angular's $resource to retrieve data from an API. The configuration of the angular $resource is as follows: Priorities: $resource (baseUrl + 'priorities/:priorityType/:uuid/all', {}, { query: { method: 'GET', ...

The removal of a JQuery element can result in causing the webpage to become unresponsive and lead to

When attempting to create a loop in JQuery to remove elements from my HTML, I encountered an issue where the function caused my browser to hang and become unresponsive. Here is the JQuery code I used: function removeElement(){ var i =0; ...

Reactjs Promise left hanging in limbo

How can I resolve the pending status of my promise? I have a modal with a form submit in it, where I am trying to retrieve the base64 string of a CSV file. While my code seems to be returning the desired result, it remains stuck in a pending state. c ...

How can I adjust the time in a range slider using AngularJS?

Currently, I am utilizing a Slider with draggable range in angular js for time selection. The Slider can be found here: https://jsfiddle.net/ValentinH/954eve2L/. I aim to configure the time on this slider to span from 00.00 to 24.00, with a 10-minute inter ...

Replicating JQuery/JavaScript functionalities

I'm facing a challenge with a jQuery/Javascript function that creates an array to populate a hidden field in a nested form. In order to fill the hidden field for all children, I need to call this function multiple times with different child IDs each t ...

What is the reason behind the occurrence of an error when attempting to iterate through an array of objects within my react.js component?

Here is an example of some code: class Stepper extends Component { state ={ quiz_data: [ patient_data: [ {name: "A", age: "1"}, {name: "B", age: & ...