在Angularjs 2 HTTP GET请求中以纯文本或xml的形式检索响应主体

时间:2016-10-22 05:22:44

标签: xml angular typescript

我正在尝试向返回XML的服务器发出if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, Manifest.permission.READ_EXTERNAL_STORAGE)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE); // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an // app-defined int constant. The callback method gets the // result of the request. } } 请求:

get

但是,let text = ""; this.http.get('http://example.com', {headers : headers}) .map((res:Response) => res.text()).subscribe(data => text = data); 变量是空字符串,如何检索纯文本以转换为XML或如何直接获取XML?

2 个答案:

答案 0 :(得分:6)

您的代码对我来说非常合适,也许您在http调用完成之前尝试访问text?请记住,http调用是异步操作。试试这个,你会发现它完美无缺:

let text = "";
this.http.get('https://jsonplaceholder.typicode.com/posts')
.map((res:Response) => res.text())
.subscribe(
    data => {
        text = data;
        console.log(text);
     });

答案 1 :(得分:0)

你的方法看起来不错。试试这个

this.http.get('http://example.com', {headers : headers})
     .map((res:Response) => { return res.text() }).subscribe(data =>  {text = data});