2017-04-26 94 views
0

我正在将Ionic v1应用程序迁移到Ionic v2。在我的一个方法中,我调用了一个WCF服务。在AngularJS我不喜欢这样写道:Http post Angular2

$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#的服务收到一个错误,说我发送给我的函数格式是' RAW',等待它发送JSON和Angular 2

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); 
}); 

不工作,

但是,如果我从邮差测试这个工作

回答

1

此:

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

这:

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

是非常矛盾和不一致。

当您向Web服务器发出HTTP请求时,请务必保持一致,以便对请求进行编码。所以如果打算送一个JSON体确保您指定适当的Content-Type请求头,这样服务器就知道如何处理这个有效载荷:

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

谢谢回答。当我更改该内容类型时,出现错误“405方法不允许” – sioesi

+0

那么,您将需要修复您的网络服务器,以便它接受POST请求。 405状态码通常表示Web服务器不理解您正在使用的HTTP动词。 –

+0

我将添加我的服务,以便您可以看到它。 – sioesi

0

除了什么达林说,我会说你是不正确使用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);