[英]How to parse Json response in Angular 4
嗨,我是Ionic的初學者,從事角度應用程序開發,並使用以下代碼進行Http調用,並且我以json格式獲取響應,現在我想在列表中顯示響應標題 ,我嘗試了很多但沒有得到結果,請提供一些幫助我
https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot
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>
您使用錯誤的鍵來獲取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;
});
如果您使用的是httpClient
則無需使用json()
還請刪除{observe:'response'}
因為在用例中無需這樣做。
使用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);
});
試試這個
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;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.