如何在Angular模板中访问嵌套的jsondata,我尝试使用ngFor对此不起作用

时间:2018-10-23 12:24:52

标签: json angular typescript

我正在尝试访问我的角度模板中的JSON数据,但我不知道该怎么做:

JSON数据:

{
    "data": {
        "active_cryptocurrencies": 2050, 
        "active_markets": 15110, 
        "bitcoin_percentage_of_market_cap": 53.85, 
        "quotes": {
            "USD": {
                "total_market_cap": 207937227143.0, 
                "total_volume_24h": 10373130891.0
            }
        }, 
        "last_updated": 1540293278
    }, 
    "metadata": {
        "timestamp": 1540292653, 
        "error": null
    }
}

mycomponent.ts

jsonData: any[];

private _url = 'https://api.coinmarketcap.com/v2/global/'; 

constructor(private http: Http) {
    http.get("https://api.coinmarketcap.com/v2/global/")
        .subscribe(response =>{
            this.jsonData = response.json().data.quotes;
            console.log(this.jsonData);
         });
}

因此,我试图在角度模板中显示这些详细信息,但显示为cannot find-a-differ-supporting-object-object-object-of-type-object-ngfor

您能帮我一下,因为这里的json有点乱吗? 我只想在我的html模板中显示JSON数据。

1 个答案:

答案 0 :(得分:-1)

编辑:

import { Component, Input, OnInit,Injectable } from '@angular/core';
import { Http, Headers } from  '@angular/http' ;

@Component({
  selector: 'hello',
  template: `
  Hello, Angular
    <ul *ngFor="let item of data">      
      <li>active_markets :{{item.active_markets}}</li>
      <li>bitcoin_percentage_of_market_cap:{{item.bitcoin_percentage_of_market_cap}}</li>
      <li>last_updated: {{item.last_updated}} </li>
      <li>
          <ul *ngFor="let q of item.quotes">        
             <li>total_market_cap: {{q.total_market_cap}}</li>
            <li>total_volume_24h: {{q.total_volume_24h}}</li>
          </ul>
      </li>
    </ul> 
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  data:any=[];
  private _url = 'https://api.coinmarketcap.com/v2/global/';

  constructor(private http: Http) {}

  async ngOnInit(){    
    let obj =(await this.http.get(this._url).toPromise()).json(); 

您应该转换json对象

   this.data= Object.keys(obj).map(function(e){
    Object.keys(obj[e]).forEach(function(k){
          if(typeof obj[e][k] == "object" && (obj[e][k]!=undefined || obj[e][k]!=null )) {
            obj[e][k] = Object.keys(obj[e][k]).map(function(l){
             return obj[e][k][l];
            });
          }
        }return obj[e];
        });
    );}}