代码之家  ›  专栏  ›  技术社区  ›  AbhiRam

如何解析角度4中的JSON响应

  •  0
  • AbhiRam  · 技术社区  · 6 年前

    嗨,我是开发Angular应用程序的爱奥尼亚初学者,使用下面的代码进行HTTP调用,我得到了json格式的响应,现在我想要显示响应 在名单上,我试了很多,但没有取得结果。有人能帮我吗?

    https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot

    主页.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;
          });
    

    <ion-content padding>
      <ion-list>
      <ion-item *ngFor="let c of countries">
        <h2>{{c.title}}</h2>
      </ion-item>
    </ion-list>
    </ion-content>
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Pardeep Jain    6 年前

    您使用了错误的键来获取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 那就不用用了 {observe:'response'} 因为在您的用例中不需要这个。

        2
  •  0
  •   Parvej Mallick    6 年前

    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);
    });
    
        3
  •  0
  •   keval nayak    6 年前

    试试这个

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