2017-08-13 14 views
3

我试图访问一个将XML数据传回的web服务。在过去,我使用了一个节点服务器,并且没有任何问题地调用外部web服务。Angular 4.3.4 httpclient返回null作为订阅,但我在网络上获得了有效的http响应

现在我的目标是通过新的httpclient从我的Angular 4.3.4应用程序直接访问外部web服务。

如果我试图通过从本地主机休息服务获取数据一切正常。但是,如果我尝试获得外部服务,我有一个奇怪的行为: 在订阅中,我始终得到NULL作为服务的返回值,但如果我查看网络内部的通信,如果我看到数据被转发正确状态200.

httpClient.post(
    'http://www.fivb.org/Vis2009/XmlRequest.asmx', 
    'Request=<Requests Username="Guest" >' + 
    '<Request Type="GetBeachTournamentList" ' + 
    'Fields="Code No Name CountryCode Gender NoEvent Type">' + 
    '<Filter Types="36" />' + 
    '</Request>' + 
    '</Requests>', 
    { headers: new HttpHeaders() 
    .set('Accept', 'application/xml') 
    .set('Content-Type', 'application/x-www-form-urlencoded;') 
    }) 
    .subscribe(
    data => { 
     // here I get null 
     console.log(data); 
    }, 
    err => { 
     console.log(err); 
    } 
); 

将是巨大的,如果有人有一个想法

全样本可

回答

4

我的猜测是,你应该设置responseTypetext,请求选项内。

httpClient.post(
    'http://www.fivb.org/Vis2009/XmlRequest.asmx', 
    `Request= 
    <Requests Username="Guest" > 
    <Request Type="GetBeachTournamentList" Fields="Code No Name CountryCode Gender NoEvent Type"> 
     <Filter Types="36" /> 
    </Request> 
    </Requests>`, 
    { headers: new HttpHeaders() 
    .set('Accept', 'application/xml') 
    .set('Content-Type', 'application/x-www-form-urlencoded;'), 
    responseType: 'text' //<== set here to receive text/xml response. 
    } 
) 
2

默认情况下,HttpClient将响应解析为JSON并返回适当的JavaScript对象。但在你的情况下,响应是XML而不是JSON,所以这个逻辑失败了。

Requesting non-JSON data,需要在第二个参数指定responseType: 'text',以获得原始文本响应:

let options = { 
    responseType: 'text', 
    headers: new HttpHeaders() 
     .set('Accept', 'application/xml') 
     .set('Content-Type', 'application/x-www-form-urlencoded;') 
} 

httpClient.post(url, data, options) 
+0

这是解决方案。 非常感谢 – dide

相关问题