解析XML到JSON和订阅与Angular4
我想通过使用xml2js将XML字符串转换为JSON,然后我需要发送和订阅另一个组件的结果。解析XML到JSON和订阅与Angular4
getLastWeekSnow = function(){ let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password'));
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
xml2js.parseString(res.text(), function (err, result) {
console.dir(result); //Prints JSON object!
});
})
.subscribe(data => {
console.log(data); //Undefined !
});
}
所以console.dir(reults)给我回什么,我需要,但在认购(执行console.log(数据))我得到了一个未定义。
为什么我会在订阅中获得undefined,但在.map中获取正确的Object?
回答:
确保返回数据,否则就不能订阅
getLastWeekSnow = function(){ let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*');
headers.append("Authorization", "Basic " + btoa('user' + ":" + 'password'));
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.get(`${this.APIUrl}`, {headers:headers})
.map(res => {
let data;
xml2js.parseString(res.text(), function (err, result) {
console.dir(result); //Prints JSON object!
data = result
});
return data;
})
.subscribe(data => {
console.log(data); //Undefined !
});
}
以上是 解析XML到JSON和订阅与Angular4 的全部内容, 来源链接: utcz.com/qa/258956.html