Successfully Passing GET Parameters to ngResource in AngularJS

I'm struggling to figure out how to pass a simple id parameter to my created resource.

The service in question is:

angular.
  module('shared.testUser').
  factory('TestUser', ['$resource',
    function($resource) {
      return $resource('http://127.0.0.1:4001/api/testusers/:id', {id:'@userid'});
    }
  ]);

The component and controller that utilizes this service are:

angular.
  module('logIn').
  component('logIn', {
  templateUrl: 'log-in/log-in.template.html',
controller: ['TestUser', function LogInController(TestUser) {
self = this;
      self.testUserSet = TestUser.query();
      self.oneUser = TestUser.get({userid:3});
      self.testVar = 20;
  }]
  });

When running the code, I encounter an error on the self.oneuser line.

Error: $resource:badcfg
Response does not match configured parameter
Error in resource configuration for action get. Expected response to contain an object but got an array (Request: GET )

I've attempted various approaches to adjust this line, but have been unsuccessful thus far.

Answer №1

Ensure that you use the same identifiers as specified in the $resource function definition.

For example, if you have this setup:

return $resource('http://127.0.0.1:4001/api/testusers/:id', {id:'@userid'});

When passing parameters to your component, make sure to bind them like {id: 1234}.

It's important to note that I modified the identifier from "userid" to "id", which aligns with how you define your own parameters within $resource. By following the correct conventions, you can avoid unnecessary complications when working with Angular.

In the context of this syntax, it's essential to understand that there is no provision for passing a body in a GET request. The params defined in https://docs.angularjs.org/api/ngResource/service/$resource are designed to bind to the placeholders you set up in $resource. It's crucial not to mix up concepts between $http and $resource.

Feel free to refer to this working plunk for further guidance.

Answer №2

In the $resource function, the second argument is used to set default parameters:

app.factory('TestUser', ['$resource',
    function($resource) {
        return $resource('testusers.json/:id', {id:'default'});
    }
]);

If you need to change the default parameter values for a GET action, simply specify the parameter name:

app.controller('MainCtrl', function($scope, TestUser) {

    var vm=$scope;

    vm.testUserSet = TestUser.query();
    vm.oneUser = TestUser.get({id:3});

Check out the live example on PLNKR

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

Steps for embedding a custom function in a switch statement

I am attempting to run a switch statement based on the argument provided to the function below. I have been trying to call different functions depending on the argument passed. However, I encountered an Uncaught ReferenceError in the beginning of the .js f ...

Tips for adding React components to an array with the help of backticks

Currently, I am attempting to populate an array with icons by extracting the name from data and concatenating "<" and "/>" around it in order to convert it into an Mui Icon. Despite renaming the imported icons to match the names in the data, when I ...

The session data is not persisting in the express-session package

I am currently learning about HTTPS and working on implementing a login/logout function. In this function, I store the userId in the session when I login using the POST method. However, when I try to retrieve user information for the next components usin ...

Launch a fresh tab using Chrome's extensions feature

Currently, I am in the process of developing a Google extension that will search for selected text on Google when the user clicks "ctrl+alt+x". Here is the mainfest for the extension: { "name": "A jQuery Chrome extension", "version": "0.1", "descri ...

Leveraging an Array of Objects in JavaScript

Need help with my JavaScript code! I want to adjust the date in a Date object by adding specific days and then save it. Here is what I have so far: let orderIdDateCorrectionDict = [ { "orderId": "2020053100", "dayCorrection": -146 }, { "orderId" ...

Angular services are equipped with a powerful tool called the $http

Encountering an issue with promises within an angular service. The problem lies with a specific method getArea in the service which aims to retrieve the name of a service area. This data is obtained from the API. However, upon obtaining the service areas a ...

Angular.js hierarchical model issue: grandchildren functionality not functioning as expected

Currently, I am delving into the world of Angular and exploring its functionalities. My main goal is to construct a hierarchical data structure that can be easily manipulated using a hierarchical view: Root: - addChild - child 1: { remove, addChild, c ...

How can I use a button created with jQuery's .html() method to conceal a <div>?

I am facing an issue with implementing a simple banner that should appear in an empty element only when specific values are returned by an Ajax call. In the banner, I want to include a Bootstrap button that hides the entire div when clicked. Due to my la ...

Choose a date range from the date picker

I am currently attempting to combine two dates using a rangepicker. Below is the command used to select the date: Cypress.Commands.add('setDatePickerDate', (selector, date) => { const monthsShort = [ 'janv.', 'févr.& ...

Chrome is struggling to load pages, forcing users to scroll endlessly to find the content they are looking for

Encountering a problem where Chrome occasionally displays a particular page off-screen. Currently using Mac OSX, working on a Backbone.js App with client-side development only, no PHP/Node. The page is loading completely off-screen, requiring me to scrol ...

Accessing properties in JavaScript using square brackets

When I input the following code into my Chrome console: var object = {0:0, 1:1} I am able to retrieve the values by calling object[0] and object[1]. Surprisingly, even when I use object["0"] and object["1"], I still get the same results. Then, if I redef ...

Switch between class and slider photos

I am currently having an issue toggling the class. Here is the code I am working with: http://jsfiddle.net/h1x52v5b/2/ The problem arises when trying to remove a class from the first child of Ul. I initially set it up like this: var len=titles.length, ...

What is the most efficient method for defining a string structure in TypeScript?

Consider the following example of a JavaScript object: const myObject = { id: 'my_id', // Base value which sets the structure for the following values (always pascal case). upperID: 'MY_ID', // Uppercase version of `id`. camel ...

Tips for accessing external JSON data and implementing it in a JavaScript navbar

Starting with this as a reference point, I am looking to modify it to read data from an external data.json file. My familiarity with JQuery is limited, but I have been able to achieve the desired outcome by using var JSON = {...same structure as from da ...

Learn how to build a table using JSON data in conjunction with angularJS and PHP backend for your web

Currently, I am working on a project that involves PHP backend and AngularJS. In the login.php file, there is a query which returns a result saved in variable $result. This result is then passed to app.JS where it is stored in a cookie and displayed in the ...

"Troubleshooting problem with fetching JSON data for Highcharts

As a relative newcomer to web development, my usual focus is on server-side work. Currently, I'm diving into a fun little electronic project where a Netduino server handles JSON requests within my LAN. The JSON response format from the Netduino looks ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Characters that have been escaped are showing up when adding them to an HTML element

Through an AJAX call, I am fetching HTML code and appending it to an existing HTML element. However, the appended code includes escaped characters, leading to broken HTML with elements appearing scattered like this: Contact Us ▸<\/a><\ ...

Unable to .map two separate arrays within the same table row, <tr>

I am currently facing an issue with mapping entries to a table. The entry I am working with has a column that can contain multiple values, requiring the creation of sub-rows within the same row. I have provided an example image below to illustrate the desi ...

Implementing HTML5 form validation without a submit button and using a personalized error message

I am facing an issue with displaying the HTML5 inline validation bubble without the use of a submit button. The catch is, I am not allowed to use jQuery, only vanilla JavaScript. Here is the HTML I am working with: <a id="send" href="#">Send</a& ...