我正在尝试使用新的 Public API V2 CoinMarketCap,但我在这方面遇到了一些困难。
JSON:
https://api.coinmarketcap.com/v2/ticker/?limit=10
我的模型硬币:
export class Coins {
id: string;
name: string;
symbol: string;
rank: number;
price_usd: number;
price_btc: number;
_24h_volume_usd: number;
market_cap_usd: number;
available_supply: number;
total_supply: number;
percent_change_1h: number;
percent_change_24h: number;
percent_change_7d: number;
last_updated: number;
}
我的服务:
urlBase = 'https://api.coinmarketcap.com/v2/ticker/?limit=10';
getCoins() {
return Observable
.timer(0, 5000)
.flatMap(() => this.http.get(this.urlBase))
.pipe(
map(res => res),
catchError(this.handleError)
)
}
我的组件:
coins: Coins[];
getCoins() {
this.coinsService.getCoins().subscribe(
data => {
this.coins = data;
});
}
我的 html:
<div class="card card-inverse" *ngFor="let coin of coins">
输出:
ERROR Error: Cannot find a differ supporting object '[object Object]' of type
'object'. NgFor only supports binding to Iterables such as Arrays.
有什么建议吗?
谢谢
最佳答案
根据您显示的 api 数据,我看到您正在为对象而不是数组分配 this.coins
。您应该先将其转换为数组,然后将其分配给 this.coins
。
getCoins() {
this.coinsService.getCoins().subscribe(
data => {
this.coins = [];
for(let key in data){
this.coins.push(data[key]);
}
});
}
否则你也可以这样做将对象转换为数组。
getCoins() {
this.coinsService.getCoins().subscribe(
data => {
this.coins = [];
Object.keys(data).map((key)=>{ this.coins.push(data[key]) });
});
}
在你的服务文件中
getCoins() {
return this.http.get(this.urlBase).pipe(map(res => res = res.json()['data']))
}
工作 DEMO
关于javascript - Angular - 如何获取 JSON 对象的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50870752/