Using AngularJS's $http.get to pass an array of objects as parameters

I'm struggling to figure out the proper way to send an array of objects to my API using AngularJS.

FrontEnd Code:

     function fetchPrices(articles) {
            return $http.get('http://someurl/api/prices/getprices', { params: { articles: articles } }).then(function (res) {
                   // perform actions on prices
                }, function (err) {
                    // handle errors
                });
      }

The structure of Articles is as follows:

var oneArticle = {
  code: 'someCode',
  quantity: 1,
  stockUnit: 'piece'
}

API code:

[VersionedRoute("getprices")]
[HttpGet]
public IHttpActionResult RetrievePrices([FromUri]List<Article> articles) {
 // process input data
}

Article class details:

public class Article {
  public string Code {get;set;}
  public int Quantity {get;set;}
  public string StockUnit {get;set;}
}

Some inquiries:

1) Why does my API not receive any data? The "Articles" object always remains null.

2) Is this the correct methodology to follow?

Thank you

EDIT 1: After utilizing a post option, I am receiving the displayed data in my request. However, I am unsure about how to manage it within the API.

https://i.sstatic.net/pJ7rA.png

Answer №1

I finally have it up and running.

@Tomo: Your effort is much appreciated

@Naimad: I owe you an apology, you were right all along.

Here's the solution that's working:

Frontend:

function retrievePrices(products) {
            return $http.get('http://someurl/api/prices/getprices', articles).then(function (res) {
                   // process prices
                }, function (err) {
                    // handle errors
                });
      }

Backend

[VersionedRoute("getprices")]
[HttpPost]
public IHttpActionResult GetPrices([FromBody]List<Article> articles) {
 // implement processing logic here
}

Answer №2

.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
    function fetchPrices(products) {
        $http.get('http://anotherurl/api/prices/fetchprices')
        .success(function (result) {
            products: result
        }
    }
}])

Answer №3

Have you attempted this code snippet:

return $http({
            url: '/api/SomeCtrl/GetPrices',
            method: 'POST',
            data: JSON.stringify({ Article : articles }),
            headers: { 'Content-Type': 'application/json' }
        });

as well as:

public IHttpActionResult GetPrices([FromUri]Article articles) {

or

[HttpPost]
public void GetPrices(Article articles)

where instead of void, specify the return type?

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

Can you explain the inner workings of the sort function in JavaScript, including how it utilizes the compare

I'm curious about how the sort function operates in JavaScript, specifically in conjunction with the compare function. According to what I've read, if you have an array and use the code array.sort(compare), it's stated that if the compare fu ...

Customize the number of slides in Glide.js after navigating using the controls

I have incorporated a glide JS carousel to display content in a carousel format. The documentation for this repository can be found on their official website as well as on Github. Here is my current code snippet: jQuery( window ).load(function() { va ...

The ModalPopupExtender has the ability to automatically close

I implemented a ModalPopupExtender to display a panel with a textbox inside. I added some code for the textbox's textchanged event, but every time the focus leaves the textbox, the popup closes automatically. Can anyone suggest a solution to this prob ...

implementing the CSS property based on the final value in the loop

I have created multiple divs with a data-line attribute. I am trying to loop through each div, extract the individual values from the data-line attribute, and apply them as percentages to the width property. However, it seems to only take the last value an ...

Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component: <template> <div> <button data-cy="testBtn" @click="btnClick()&q ...

What is the recommended approach for formatting a JSON response to a Restful API call?

I'm in the process of determining the most effective way to return a JSON response for a Restful API call. After reading numerous blog and tutorial articles, I have come across various opinions on this matter. One proposed method suggests that every ...

The sessionToken is invalidated upon the user updating their password

My mobile hybrid app is connected to an expressJS server that acts as the backend for proxying requests to parse.com through the REST API. Additionally, I have implemented user authentication using express with a Single Sign-On (SSO) provider. Although I f ...

Tips for accessing the value of an unchecked checkbox in AngularJS

This is a snippet of HTML code: <p> <input type="checkbox" ng-model='add_product.kids' class="filled-in" id="filled-in-box1" /> <label for="filled-in-box1">Kids</label> </p> My goal is to obtain the value "fa ...

How can I dynamically insert HTML content into a data-attribute using JavaScript?

I have been trying to insert a variable that includes HTML code into a DATA attribute (a href ... data-content= ...), but it isn't functioning properly. The code I input seems to delete certain characters and as a result, it does not display correctly ...

Using jQuery to store the selection made in a select element option

Hello everyone, I need some help with saving the selected option on my form by the user. I am not sure how to accomplish this. Let me give you a brief overview of my setup... On my home page, I have a form that looks like this: <form class="form-home ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

Tips for enabling unrestricted unencoded HTML in XmlNode or XmlElement with XmlSerializer

Looking for a solution to generate an XML element that can handle a string of text containing HTML or other valid XML elements. Here's an example: "Test text with <strong>custom nodes</strong> that shouldn't be encoded" I've at ...

Sometimes, the `undefined` TypeError can unexpectedly pop up while making Ajax calls

Here is my issue with AJAX request and response: I have around 85 HTML pages that all use the same AJAX request. However, when working with these files, I sometimes encounter the following error. AJAX $(document).ready(function(){ localStorage.setIte ...

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Unable to retrieve custom date picker value with React Antd

I have implemented a custom datepicker for entering dates in the 'MMDD' or 'MMDDYY' format. The date value is stored in state and used in the datepicker component as a controlled component. However, upon form submission, the datepicker ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...

A shared webpage featuring both a server and client-side form

I am facing an issue with having two forms on an ASP.NET page. One form is the main form with runat="server" attribute, and the other is a simple form for searching with just one input field. The search form code is as follows: <form method="post" id=" ...

Are there Alternatives for Handling Timeout Exceptions in Selenium WebDriver?

Currently, utilizing Selenium WebDriver with node.js to scrape extensive weather data spanning multiple decades from a site that loads only one day's worth of data per page at full resolution. The process involves navigating between URLs and waiting f ...