angular - 如何在 Angular 4 中解析 Json 响应
问题描述
嗨,我是 ionic 的初学者,使用 Angular 应用程序开发并使用以下代码进行 Http 调用,我得到了 json 格式的响应,现在我想在列表中显示响应标题,我尝试了很多但没有得到结果可以请有人帮助我
接口地址:
https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot
home.ts:
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot',{ observe:'response'}).subscribe( res => { console.log(res) ;
var info=JSON.parse(JSON.stringify(res));
this.countries = info.data.children;
});
主页.html:
<ion-content padding>
<ion-list>
<ion-item *ngFor="let c of countries">
<h2>{{c.title}}</h2>
</ion-item>
</ion-list>
</ion-content>
解决方案
您使用错误的键来获取 HTML 部分中的值,代码应该是 -
<h2>{{c.data.title}}</h2>
代替
<h2>{{c.title}}</h2>
还有你为什么要使用parse
then stringify
,只需使用json()
这样的赋值 -
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot', {observe:'response'}).subscribe( res => {
console.log(res) ;
let response = res.body;
this.countries = response.data.children;
});
工作示例
更新
如果您正在使用,httpClient
则无需使用json()
也删除{observe:'response'}
,因为在您的用例中不需要这个。
推荐阅读
- python - numpy.ndarray 中的行组合
- docker - 具有不同标签的相同图像的多个 docker push 导致 blob 上传未知
- javascript - 函数没有在 javascript 中被调用。由 WebPack 捆绑
- python-3.x - Git post-recieve hook 来运行 virtualenv、Django 和各种 python 脚本
- javascript - 如何在使用大量子元素更改元素位置时提高 React 性能
- laravel - Laravel Restful api 生产服务器配置
- mysql - 无法将数据库导入我的实时 phpmyadmin
- django - Django 使用电子邮件验证后端
- bash - bash 在 systemctl 中。错误 2 启动时启动
- c++ - 如何在 C++ 中写入 Apache Arrow 羽毛文件?