繁体   English   中英

Http发布Angular2

[英]Http post Angular2

我正在将Ionic v1应用程序迁移到Ionic v2。 在我的一种方法中,我调用了WCF服务。 在AngularJS中,我这样做:

$http({
 method: 'POST',
 url: url,
 data: JSON.stringify({ dato: 11 }),
 dataType: "json",
 contentType: "application/x-www-form-urlencoded"
})

在Angular2中是这样的:

let data = JSON.stringify({ dato: 11 });
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers });
this.http.post(url, data, options)
.subscribe(data => {
  console.log(data);
}, error => {
  console.log("Error");
});

但是,我从C#服务收到一个错误,并说我在等待它使用Angular 2发送JSON时发送给函数的格式为'RAW'

我在AngularJS中发生了此错误,但是通过添加我之前在本文中留下的代码解决了该错误。

编辑

我的WCF服务:

[OperationContract]
[WebInvoke(UriTemplate = "/GetCaptaciones", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json , BodyStyle = WebMessageBodyStyle.Wrapped)]
List<Captacion> GetCaptaciones(int id_captador);

let data = JSON.stringify({ id_captador: 11 });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url + "/GetCaptaciones", data, options).subscribe(data => {
  console.log(data);
});

不工作

但是如果我从POSTMAN进行测试,则可以

这个:

let data = JSON.stringify({ dato: 11 });

和这个:

let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});

非常矛盾和前后矛盾。

当您对网络服务器发出HTTP请求时,请尝试保持一致,以了解如何对请求进行编码。 因此,如果打算发送JSON正文,请确保指定正确的Content-Type请求标头,以便服务器知道如何处理此有效负载:

let headers = new Headers({ 'Content-Type': 'application/json'});

除了达林所说的以外,我还要说的是您没有正确使用BodyStyle = WebMessageBodyStyle.Wrapped

请参阅您的wcf方法需要一个参数,这样您就可以不使用wrappedrequest属性。

[OperationContract]
[WebInvoke(UriTemplate = "/GetCaptaciones", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json)]
List<Captacion> GetCaptaciones(int id_captador);

包装的请求意味着在输入属性的顶部应该有一些包装对象,WCF方法将其作为参数。

所以像这样

 var input =
        {
            "CaptacionesInput": 
            {
                "id_captador": 11
            }
        };

现在,wcf方法变得像

List<Captacion> GetCaptaciones(CaptacionesInputType CaptacionesInput);

暂无
暂无

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

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