我不喜欢从 API 返回到我的 Angular 4 应用程序的数据。
这是 JSON 的示例,我不关心美元,但这就是我正在处理的数据类型
最终目标是在页面上显示
Coin Price
BTC $4,281.28
ETH $294.62
etc..
JSON
{
"BTC": {
"USD": 4281.28
},
"ETH": {
"USD": 294.62
},
"LTC": {
"USD": 43.4
},
"EOS": {
"USD": 1.7
},
"DASH": {
"USD": 197.69
}
}
服务文件
getAllCoins(): Observable<Response> {
return this.http.get(this._url)
.map(res => res.json())
.do(data => console.log('coins ' + JSON.stringify(data)))
.catch(this.handleError)
}
订阅coinService的组件文件
this.coinService.getAllCoins()
.subscribe(
(data) => {
for (let key in data) {
this.coinsList.push(data[key]);
console.log('key', key)
}
},
(error) => console.log("error : " + error)
);
最后是模板html
<div *ngFor="let coin of coinsList">
<span>{{coin | json}}</span>
</div>
我可以看到key
将在console.log中显示BTC等。
然后在页面上我看到
{ "USD": 4234.31 }
但我不想看到括号之类的东西,而是硬币(BTC)和价格 -
我应该将不同的数据推送到我的数组中吗? coinsList = [];
最佳答案
请更新您的代码,如下所示:
this.coinService.getAllCoins()
.subscribe(
(data) => {
for (let key in data) {
this.coinsList.push({coinName:key,price:data[key].USD}); //change is here
console.log('key', key)
}
},
(error) => console.log("error : " + error)
);
并在 View 中
<div *ngFor="let coin of coinsList"> <span>{{coin.coinName}} {{coin.price}}</span> </div>
这应该会产生您想要的结果。
关于javascript - Angular 4 显示其中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45727951/