简体   繁体   English

AngularJs $http.get:将对象数组作为参数发送

[英]AngularJs $http.get: Sending array of objects as params

I am having issues with finding the correct way to send an array of objects to my API using AngularJS.我在寻找使用 AngularJS 将对象数组发送到我的 API 的正确方法时遇到问题。

FrontEnd Code前端代码

     function getPrices(articles) {
            return $http.get('http://someurl/api/prices/getprices', { params: { articles: articles } }).then(function (res) {
                   // do something with prices
                }, function (err) {
                    // handle error
                });
      }

Articles are of the type文章属于以下类型

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

Api code接口代码

[VersionedRoute("getprices")]
[HttpGet]
public IHttpActionResult GetPrices([FromUri]List<Article> articles) {
 // do something with input
}

Article class文章类

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

Some questions:一些问题:

1) Why do I not receive any data on my API. 1) 为什么我的 API 没有收到任何数据。 Articles is always null文章始终为空

2) Is this the right approach? 2)这是正确的方法吗?

Thanks谢谢

EDIT 1: Using a post option I receive following data in my request but I still don't know how to handle it on the API.编辑 1:使用 post 选项我在我的请求中收到以下数据,但我仍然不知道如何在 API 上处理它。

在此处输入图片说明

I finally got it working.我终于让它工作了。

@Tomo: Thanks for the effort @Tomo:感谢您的努力

@Naimad: My apologies, you were right from the beginning. @Naimad:我很抱歉,你从一开始就是对的。

Here is the working solution:这是工作解决方案:

Frontend:前端:

function getPrices(articles) {
            return $http.get('http://someurl/api/prices/getprices', articles).then(function (res) {
                   // do something with prices
                }, function (err) {
                    // handle error
                });
      }

Backend后端

[VersionedRoute("getprices")]
[HttpPost]
public IHttpActionResult GetPrices([FromBody]List<Article> articles) {
 // do something with code
}

Have u tried你试过吗

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

and

public IHttpActionResult GetPrices([FromUri]Article articles) {

or或者

[HttpPost]
public void GetPrices(Article articles)

where instead of void you put whatever you are returning ?你把你要返回的东西放在哪里而不是 void ?

.controller('LoginController', ['$scope', '$http', function ($scope, $http) {
    function getPrices(articles) {
        $http.get('http://someurl/api/prices/getprices')
        .success(function (data) {
            articles: data
        }
    }
}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM