typescript 在 Angularjs 2 HTTP GET 请求中以纯文本或 xml 形式检索响应正文
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40188631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve Response body as plain text or xml in Angularjs 2 HTTP GET request
提问by Gtopuria
I am trying to make get
request to server which returns XML:
我正在尝试向get
返回 XML 的服务器发出请求:
let text = "";
this.http.get('http://example.com', {headers : headers})
.map((res:Response) => res.text()).subscribe(data => text = data);
But, text
variable is empty string, how can I retrieve plain text to convert to XML or how can I directly get XML?
但是,text
变量是空字符串,如何检索纯文本以转换为 XML 或如何直接获取 XML?
回答by Stefan Svrkota
Your code works perfectly for me, maybe you are trying to access text
before http call is finished? Have in mind that http calls are asynchronous operations. Try this out and you will see that it works perfectly:
您的代码非常适合我,也许您正在尝试text
在 http 调用完成之前访问?请记住,http 调用是异步操作。试试这个,你会发现它工作得很好:
let text = "";
this.http.get('https://jsonplaceholder.typicode.com/posts')
.map((res:Response) => res.text())
.subscribe(
data => {
text = data;
console.log(text);
});
回答by Sefa
Your approach looks good. Try like this
你的方法看起来不错。像这样尝试
this.http.get('http://example.com', {headers : headers})
.map((res:Response) => { return res.text() }).subscribe(data => {text = data});