如何在Angular 4中解析Json响应

时间:2018-06-19 07:14:53

标签: angular ionic3

嗨,我是初学者在离子角度应用程序开发中使用以下代码进行Http调用,我得到了json格式的响应,现在我想在列表中显示响应 title ,我尝试了很多但没有得到结果可以帮助我一些人

Api网址:

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;
      });

home.html的:

<ion-content padding>
  <ion-list>
  <ion-item *ngFor="let c of countries">
    <h2>{{c.title}}</h2>
  </ion-item>
</ion-list>
</ion-content>

3 个答案:

答案 0 :(得分:2)

您使用了错误的密钥来获取HTML部分中的值,代码应为 -

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

而不是

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

为什么您使用parse然后使用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;
    });

Working Example

更新

如果您使用的是httpClient,则无需使用json()同时删除{observe:'response'},因为您的用例中不需要这样做。

答案 1 :(得分:0)

使用rxmap

import 'rxjs/add/operator/map';

this.http.post('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot',{ observe:'response'}).map(res => res.json()).subscribe(data => {
   console.log(data.data);
});

答案 2 :(得分:0)

试试这个

this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot',{ observe:'response'}).subscribe( res => { console.log(res) ;          
      this.countries = info['data'].children;
  });