在角

2017-04-05 12 views
0

訪問HTTP嵌套JSON數據下面是有問題的部件:在角

@Component({ 
    selector: 'my-app', 
    template: ` 
    {{tests | json}} 

    <div *ngFor='let test of tests'> 
     <div *ngFor='let x of test.A.B'> 
      <div *ngFor='let y of x.C.D'> 
      writerid:{{y.writerid}} <br> 
      content:{{y.content}} <br> 
      writedt:{{y.writedt }} <br> 
      </div> 
     </div> 
    </div> 
    `, 
}) 

public tests: any[]; 

構造從這裏的API獲取JSON數據:

constructor(private _http: Http) { 
    _http.get(this.API_URI).subscribe(result => { 
     this.tests = result.json(); 
    }); 
    } 

這是http(API_URI)我JSON數據,印刷通過{{tests | json}}(在@Component,模板):

{ 
    'A': { 
    'B': [{ 
     'C': { 
     'D': [{ 
      'content': 'content_test1', 
      'writedt': '2017-02-08 00:00:00', 
      'writerid': 'writerid_test1' 
      }, { 
      'content': 'content_test2', 
      'writedt': '2017-02-08 00:00:00', 
      'writerid': 'writerid_test1' 
      }, { 
      'content': 'content_test3', 
      'writedt': '2017-02-08 00:00:00', 
      'writerid': 'writerid_test2' 
      }, { 
      'content': 'content_test4', 
      'writedt': '2017-02-08 00:00:00', 
      'writerid': 'writerid_test2' 
     }] 
     } 
    }] 
    } 
} 

我得到的錯誤是這樣的:

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

我該如何解決?

+0

讓我們開始明目張膽:'tests' JSON格式是JSON對象* *,而不是一個JSON *陣列*,這就是爲什麼你不能迭代它。 – Makoto

回答

0

看看你的JSON,它的對象,但ngFor適用於數組類型

<div *ngFor='let x of tests.A.B'> 
      <div *ngFor='let y of x.C.D'> 
      writerid:{{y.writerid}} <br> 
      content:{{y.content}} <br> 
      writedt:{{y.writedt }} <br> 
      </div> 
     </div> 
    </div> 

也就是說你得到這個錯誤的原因。

錯誤

  1. <div *ngFor='let test of tests'> - 測試是對象類型,而不是物體或陣列的集合。

LIVE DEMO

+0

它工作在本地JSON數據,但是當我從HTTP GET數據,如 構造函數(私人_http:HTTP){ _http.get(this.API_URI).subscribe(結果=> { this.tests = result.json( ); }); } 錯誤類型錯誤:無法讀取的不確定 –

+0

你可以使用我的演示plunker財產「_source」和創建它使用JSON文件HTTP調用 – Aravind

+0

這是我真正的JSON數據仍然不起作用TT 錯誤類型錯誤:不能讀取屬性 '打' 未定義 –