【发布时间】:2018-12-12 11:05:52
【问题描述】:
我已经从请求中获取了一些数据,它应该将其作为 json 对象返回,我可以将其传递给并在某些 html 中使用,但是当运行时
console.log(this.data);
我还可以看到它在文章数组中有 20 个元素,但是当我运行时它返回 undefined 或 null
console.log(this.data.__zone_symbol__value);
对于解决此问题的任何帮助将不胜感激。 :)
根据评论进行编辑:
ngOnInit() {
this.url = 'https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=c6aecd1cd1de49edaca2544076713c45';
this.Newsdata = this.FetchHeadlines(this.url);
console.log(this.Newsdata);
console.log(this.Newsdata.__zone_symbol__value);
}
get(url: string): Promise<any> {
return new Promise((resolve, reject) => {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = () => {
if (req.status === 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = () => {
reject(Error('Network Error'));
};
req.send();
});
}
FetchHeadlines(url: string): Promise<any> {
console.log("Entered FetchHeadlines");
return this.get(url).then(JSON.parse).catch(error => {
console.log('getJSON failed for', url, error);
throw error;
});
}
【问题讨论】:
-
展示你的获取价值方法。我必须知道你在做什么。然后很容易为您提供帮助。
-
我已经为你编辑了@KarnanMuthukumar
-
iam 更新了实现您的方案的新方法。请尝试一次并告诉我。
-
console.log(JSON.stringify(this.Newsdata, null, 2));应该给你一个更具可读性的输出开始。
-
@Dylan Anelezark 我试过你的方法做了一些改变。让我们试一次,让我知道。
标签: html css json angular typescript