AngularJS $resource sends the id as a query parameter rather than including it in the URL

I'm trying to retrieve data from a rest API by using the product id as part of the URL, rather than as a query parameter.

Here is the factory code:

.factory('Products', ['$resource',
    function($resource) {
        return $resource('products/:productId', {
            productId: '@id'
        }, {
            query: {
                isArray: false
            },
            update: {
                method: 'PUT'
            }
        });
    }
])

This is how the controller looks like:

$scope.getProduct = function(id, from) {
    $scope.product = Products.get({ id: id }, function(){
        console.log($scope.product);
    });
}

When I access the URL, it currently appears as:

/products?id=5426ced88b49d2e402402205

Instead of the desired format:

/products/5426ced88b49d2e402402205

Does anyone have any insights on why this might be happening?

Answer №1

When making a call to Products.get() within the controller, ensure that you are using the correct parameter name as per your definition of the $resource. Instead of using "id", make sure to use "productId". Modify your call like this:

Products.get({ productId: id })

Referencing the documentation for $resource, it explains how key values are handled:

The parameter object's keys are matched with the url template first, and any extra keys are added to the query string after the ?.

If "id" is not recognized as a parameter in the URL, it will be appended to the query string. Make sure to adjust accordingly.

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

What is the best way to extract a thumbnail image from a video that has been embedded

As I work on embedding a video into a webpage using lightbox, I'm looking for advice on the best design approach. Should the videos be displayed as thumbnails lined up across the page? Would it be better to use a frame from the video as an image that ...

How can VueJS dynamically incorporate form components within a nested v-for loop?

I've encountered a challenge while working on my project. Here is the form I'm currently using: https://i.sstatic.net/LyynY.png Upon clicking the 'New Deal Section' button, a new section like this one is created: https://i.sstatic.n ...

Handle changes to input values on ng-click even if they were made outside of Angular's control

Looking to pass input values on ng-click even when they are changed outside of Angular. Everything works fine when manually typing, but once the inputs have dynamic values, ng-click passes empty form data. Below is the HTML code snippet: <form id="form ...

JavaScript code to allow two textboxes to be enabled at the same time when a checkbox is

One question I have regarding the code snippet below : <input id="myCheckBox" type="checkbox" name="alamatCat" onClick="apply(this.checked, 'textBox3', 'textBox4')"> OT Date </td> <td> From <input id="text ...

I am looking to halt the AJAX requests within an asynchronous function after reaching a limit of 10 requests

I've been working on an async function that sends AJAX requests based on the previous response. The function is functioning properly, but it's sending multiple requests in quick succession. I need to implement a 5-second interval between each req ...

Initializing functions and variables with ng-init

What is the correct way to implement the code below in angular js? I need to run the loader method and set some variables as well. ng-init="loader()" data-ng-init="firstName='John'" ...

Converting a JavaScript array to a PHP array using POST request

In my JavaScript script, I have the following code: cats = []; cats.push(cat1); cats.push(cat2); $.post( URL+"/edit-article.php", { id: artId, title: "PZujF0 wxKLCW", content: "ILEn3o oU9Ft6oU5", author: author, cat_id: cats } ).done(function( data2 ) ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

The section element cannot be used as a <Route> component. Every child component of <Routes> must be a <Route> component

I recently completed a React course on Udemy and encountered an issue with integrating register and login components into the container class. The course used an older version of react-router-dom, so I decided to upgrade to v6 react router dom. While makin ...

error occurred while looping through json array

i am encountering an issue with a code that keeps returning an "undefined" message instead of the expected HTML output. Purpose of function: the aim of the following function is to display notifications in a manner similar to those on Facebook. The code se ...

Parse the HTML document using an HTTP request to access the Document Object Model (DOM)

I am facing an issue with accessing elements of an HTML page through JavaScript. I have tried different methods, but I keep getting the error message: CORS header "Access-Control-Allow-Origin" missing. Here is the code snippet I tried: <!DOCTYPE html&g ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

Uploading a Node.js Package to GitHub Packages - Issue ENEEDAUTH

Hello everyone, I am currently attempting to deploy my NPM package to GitHub packages using the following yaml configuration: # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created # For m ...

Tips for managing this JavaScript JSON array

Here is an example of a JSON array: var data = { name: 'Mike', level: 1, children: [ { name: 'Susan', level: 2, }, { name: 'Jake', level: 2 }, { name: 'Roy', level: 2 }, ...

I'm trying to create a drop-down list in JS that will save selected options to a database using PHP. I'm feeling a bit lost, anyone

My goal is to upload a pdf file with specific options that determine its category. The challenge arises when creating multiple options, as the second option depends on the first choice and involves JavaScript functionality for which I am unsure how to stor ...

Error: Property 'config' cannot be accessed because it is null

Upon transferring my Angular project from my local computer to a Linux server, I attempted to launch the project using ng serve but encountered an issue where it opened a new file in the console editor instead. After some investigation, I tried running np ...

What is the process for storing form data into a text file?

Despite seeing similar questions in the past, I am determined to get to the bottom of why this code isn't functioning as expected. My goal is to input form data into a .txt file using a post request. While I lack extensive knowledge of PHP, I am pieci ...

Unlocking Node.js packages within React JS is a seamless process

Currently, I am developing a React Serverless App with AWS. I am looking for ways to incorporate a Node JS specific package into the React JS code without requiring Node JS on the backend. One package that I need access to is font-list, which enables list ...

Retrieve the v-id-xx attribute value for scoped styling in a Vue Single File Component

When using pure JavaScript to add elements in a Vue Single File Component, the added elements are missing the v-id-xx attribute for scoped CSS. Is there a way to retrieve the component's v-id-hash value using only JavaScript? ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...