javascript - Angular - 如何获取 JSON 对象的结果?

标签 javascript json angular api

我正在尝试使用新的 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/

相关文章:

javascript - 鼠标悬停/移出事件时出现奇怪的动画行为

javascript - 如何通过在 React 中克隆元素来向特定元素添加 prop?

javascript - 如何使用 typescript 检查对象内部的键和值

javascript - 在表格中显示 Angular 中单个对象的数据时出现问题

angular - 每 10 秒运行一次 API 调用

javascript - 我的谷歌图片搜索中没有图片

python - 如何在Python中从JSON获取嵌套字典

java - Android 错误 : invoke a null object. JSON/Volley

javascript - 变量没有被正确分配,可能的范围问题(在 getJSON() 中的 each() 中有一个开关的函数)

angular - 从 td 获取值,在 Angular 中输入