2016-07-14 55 views
0

我真的使用一些自定義的管道管JSON角2

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

用於解析對象JSON文件

"system": 
     { 
       "memory": 
       { 
        "total":12425734566, 
        "used":4725959680, 
        "free":8947874816, 
        "actualfree":4221499392, 
       "actualused":452335104, 
       "swaptotal":4296819712, 
       "swapused":0, 
       "swapfree":4296819712 
       }, 
       "uptime":" 12 days, 4:09", 
       "loadaverage":"0.00 0.00 0.00", 
       "cpu": 
       { 
        "vendor":"GenuineIntel", 
        "family":"6", 
        "model":"Intel(R) Xeon(R) CPU   E5620 @ 2.40GHz", 
        "rate":"2399.971", 
        "numofcores":4 
       } 

如何添加* ngFor該表並顯示「內存」對象,如何正確的語法?

<table> 
<thead> 
      <tr> 
       <th>Общая память</th> 
       <th>Общая используемая память</th> 
       <th>Свободная память</th> 
       <th>Используемая память размера подкачки</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr *ngFor="let service_rec of list.system.memory | keys"> 
       <td>{{ service_rec.total | keys}}</td> 
       <td>{{ service_rec.used | keys}}</td> 
       <td>{{ service_rec.free | keys}}</td> 
       <td>{{ service_rec.actualfree | keys}}</td> 
      </tr> 
     </tbody> 
    </table> 

該代碼不顯示「內存」的數據。我能如何解決這個問題?

回答

1

UPDATE 因此,我之前沒有看到的是您將過濾器應用於「* ngFor」。我只注意到應用於「< td>」元素的濾鏡。現在事情變得更有意義了。你其實並不想申請的「< TD>」的元素,這意味着它試圖兩次轉換數據(上一次在陣列中的每個對象,然後爲對象的屬性)過濾器。

現在,我有你想要做一個更好的主意,我做了一個example plunker。這演示瞭如何在沒有管道和管道的情況下實現您的目標。


語法看起來不錯,但管道名稱與用法不匹配。您將管道名稱標識爲「密鑰」,但當您在html中使用管道時,將其稱爲「密鑰」。

我不能說,但會解決您的整個問題,爲什麼你在你的變換方法使用該類型號碼「爲」財產作爲迭代器我不知道。我會在變換方法中將一些數據記錄到控制檯,以確保它正在運行並創建您期望的結果。

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

Ive得到此日誌 - >'對象{總:8256172032,使用:4889501696,免費電話:3366670336,actualfree:5602824192,actualused:2653347840 ...} actualfree:5602824192actualused:2653347840free:3366670336swapfree:14750576640swaptotal:14780719104swapused:30142464total: 8256172032used:4889501696__proto__:對象 monitoring.form.component.ts:25 [ 「使用」, 「總」, 「免費」, 「actualfree」, 「actualused」, 「swaptotal」, 「swapused」, 「swapfree」] 監測.form.component.ts:21個未定義 monitoring.form.component.ts:25 [] monitoring.form.component.ts:21 undefined',和數據顯示犯規在表 –

+0

什麼錯???? –

+0

您可以編輯您的原始代碼並進行更新以反映您放置console.log()行的位置嗎?另外,請提供您想用「for(let key value)」代碼實現的內容。在類型編號上運行「for」循環確實沒有意義。 –