【问题标题】:Angular - how to get result of a JSON object?Angular - 如何获取 JSON 对象的结果?
【发布时间】:2018-11-25 00:20:43
【问题描述】:

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

有什么建议吗?

谢谢

【问题讨论】:

标签: javascript json angular api


【解决方案1】:

你得到这个错误只是因为你在迭代一个对象。您需要对象数组进行迭代。

在您的 mycomponent 文件中尝试以下代码。

getCoins() {
this.coinsService.getCoins().subscribe(
    data => {
        let coins = [];
        for (let key in data) {
            coins.push(data['key']);
        }
      this.coins = coins;
    });
}

【讨论】:

    【解决方案2】:

    从您显示的 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

    【讨论】:

    • 您好阿米特,感谢您的回复。在这两个我都有输出:错误类型错误:无法读取未定义的属性'push'
    • 在声明期间将您的硬币初始化为coins : Coins[] = [];
    • @Michael 如果你不使用空数组[] 初始化coins 数组,你将不得不使用临时数组然后分配它。最好在函数内部进行初始化,如果不在声明期间。
    • 好的,我没有错误,但屏幕上没有返回任何内容。 html中应该怎么写?
    • 是的,它对我有用!相反 res = res.json() 只有 res = res
    【解决方案3】:

    this.coins = data.json() 或者你可以使用 observable。
    在 html 中 &lt;div class="card card-inverse" *ngFor="let coin of coins | async"&gt;
    在组件中

    coins: Observable<Coin[]>;
    

    getCoins() { this.coins = this.coinsService.getCoins(); }

    【讨论】:

      【解决方案4】:

      服务中:

      getCoins(): Observable<any> {
        const api = 'https://api.coinmarketcap.com/v2/ticker/?limit=10';
        return this.httpClient.get(api);    
      }
      

      在您的组件中:

      getCoins() {
          this.appService
            .getCoins()
            .subscribe(
              data => this.coins = data.data,
              error => console.log(error)
            );
        }
      
        coinKeys(coins) {
          return Object.keys(coins);
      }
      

      在模板中:

      <tr *ngFor="let k of coinKeys(coins )">
          <td>{{ coins[k].id }}</td>
      </tr>
      

      【讨论】:

        【解决方案5】:

        好的,我尝试了您的示例,但发现它存在一些问题。不确定你想用计时器实现什么,所以请保持简单。我得到的回复是这样的:{ data: [], metadata: [] }

        所以我假设在您的地图中,您需要像这样map(res =&gt; res.data) 进行映射以显示数据属性,例如

        我重写了一个简单的例子:

          getCoins() {
            const urlBase = "https://api.coinmarketcap.com/v2/ticker/?limit=10";
            this.http
              .get(urlBase)
              .pipe(map(res => res))
              .subscribe(res => console.log(res));
          }
        

        要获取数据属性,请将上面的映射更改为.pipe(map(res =&gt; res.data))

        为避免 ts 错误,您还可以键入: .pipe(map((res: { data: any; metadata: any }) =&gt; res.data))

        您还需要一些额外的数据映射以匹配您的 Coin 界面

        如果您找不到方法,我可以提供更多帮助;)

        【讨论】:

        • 您好 Megaklis,感谢您的回复。我有这个错误: src/app/service/coins.service.ts(34,22) 中的错误:错误 TS2339:“对象”类型上不存在属性“数据”。
        • 那是因为你没有输入数据对象。试试这个:.pipe(map((res: { data: any; metadata: any }) =&gt; res.data)) 当然应该换成更稳定的东西
        • 错误 TS2339:“void”类型上不存在属性“subscribe”。
        • 截图或sn-p怎么样?
        猜你喜欢
        • 1970-01-01
        • 2018-06-28
        • 1970-01-01
        • 2014-07-25
        • 2018-04-05
        • 2017-03-10
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        相关资源
        最近更新 更多