首页 > 解决方案 > 如何在 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>

标签: angularionic3

解决方案


您使用错误的键来获取 HTML 部分中的值,代码应该是 -

<h2>{{c.data.title}}</h2>

代替

<h2>{{c.title}}</h2>

还有你为什么要使用parsethen 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'},因为在您的用例中不需要这个。


推荐阅读