如何解决xml2js 到 JSON 的转换:无法设置未定义的属性“
我正在尝试使用 Angular 11.2.3 在 HTML 页面上显示 XML 文档。我正在使用 xml2js 解析器(下面的代码),并试图将响应转换为可用的 JSON 对象以在生成的 HTML 页面中循环 *ngFor
但我收到错误:
***Cannot set property 'objJSON' of undefined***
xml2js 解析器代码:
export class ExploreContentComponent implements OnInit {
feed: RssFeed = initialFeed;
stringJSON: any;
objJSON: any;
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.http.get(
'https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml',{
headers: new HttpHeaders(),responseType: 'text'
}
).subscribe(posts => {
xml2js.parseString(posts,function (err,result) {
console.log("rssFeed",result);
console.log("RESULT TORN UP",result.rss.channel[0].item);
this.objJSON = result.rss.channel[0].item;
console.log("RESULT TYPE",typeof(result.rss.channel[0].item));
});
});
}
}
输出:
RESULT (typeof) 作为 OBJECT 返回
结果被撕毁:
在 Chrome-Console 中显示了一个有效的数组对象...很多元素和键/值。
我尝试过的:
const json = JSON.stringify(result.rss.channel[0].item); <<-this will convert result to a string.
console.log("STRINGIED JSON",json); <<-this shows that valid string no problem
this.objJSON = JSON.parse(json); <<- Still get same error :(
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。