2017-05-08 42 views
0

我正在循環瀏覽json文件以在面板中顯示數據。但我在控制如何正確顯示數據方面遇到了一些麻煩。 這是從服務返回的json數據:在ng中顯示json文件錯誤對於

Object {Group1: Object, 
     Group2: Object} 

JSON文件數據樣本:

{ 
    "Group1": { 
     "name": "Group1List", 
     "dataFields": [..], 
     "dataQuery": {..}, 
     "id": 1, 
     "title": "Group1", 
     "content": {..} 
    }, 
} 

這是我的服務:

getGroupsData(){ 
     return this._http.get('...') 
     .map((res:Response) => res.json()) 
    } 

Component.ts:

groups: Array<any> = []; 
getGroups(){ 
    this.groupService.getGroupsData().subscribe(
     data => this.groups = data; 
    } 

H TML:

<div dnd-sortable-container [sortableData]="groups" [dropZones]="['container-dropZone']"> 
     <div class="col-sm3" *ngFor="let group of groups; let i = index" dnd-sortable [sortableIndex]="i" [dragEnabled]="dragOperation"> 
      <div class="panel panel-primary" dnd-sortable-container [dropZones]="['widget-dropZone']"> 
       <div class="panel-heading"></div> 
       <div class="panel-body"></div> 
      </div> 
     </div> 
    </div> 

當我使我的代碼在控制檯中的錯誤,指出:在標題中Error trying to diff '[object Object]'我想從JSON添加Group1,然後在我身上會顯示不同部分。

問題的根源是什麼?

回答

0

*ngFor需要[]數組,而你傳遞對象

你的樣品有不必要的嵌套層次,扁平始終是更好

您的JSON應該是這樣的

[ 
    { 
    "name": "Group1List", 
    "dataFields": [..], 
    "dataQuery": {..}, 
    "id": 1, 
    "title": "Group1", 
    "content": {..} 
    }, 
    { 
    "name": "Group2List", 
    "dataFields": [..], 
    "dataQuery": {..}, 
    "id": 2, 
    "title": "Group2", 
    "content": {..} 
    }, 
    // .... 
] 

更新:

如果你有在你的JSON方案無法控制,試圖在這裏將其壓平

getGroupsData(){ 
    return this._http.get('...') 
    .map((res:Response) => res.json()) 
    .map((obj) => Object.keys(obj).map((key)=>{ return obj[key]}) 
} 

或實現遍歷對象屬性的管道

import { PipeTransform, Pipe } from '@angular/core'; 

@Pipe({name: 'keys'}) 
export class KeysPipe implements PipeTransform { 
    transform(value, args:string[]) : any { 
    let keys = []; 
    for (let key in value) { 
     keys.push(key); 
    } 
    return keys; 
    } 
} 

並像這樣使用它

<div *ngFor="let group of groups | keys; let i = index"> 

</div> 
+0

我同意你的看法,但是我不能改變json格式,並保持我的狀態。 – bluePearl

+0

@bluePearl我已經更新了答案 –

+0

,所以我在渲染時沒有得到錯誤,但是當我嘗試從json打印數據時,出現未定義的錯誤。 '{{group [i] .title}}' – bluePearl

1

*ngFor需要一個數組,但它看起來像你正在傳遞一個對象。

如果你不能改變的JSON響應,並且您知道組的名稱預先,您可以將對象的數組:

this.groups = [data.Group1, data.Group2, // etc]

0

您的組件更改爲:

groups: Array<any> = []; 
getGroups(){ 
    this.groupService.getGroupsData().subscribe(
     data => this.groups = data.Group1.dataFields; 
    } 

爲什麼?

因爲,你希望你的groups組件屬性是一個數組。 因此,在您的訂閱處理程序中,data將引用整個JSON對象,並且您只關心結果的Group1屬性。

+1

我想讓ngFor循環經過Group1,Group2,Group3,因爲我有多個組。你的代碼是否意味着我將不得不爲每個組分別調用'data => this.groups = data.Groups2 ...'? – bluePearl