2016-12-02 34 views
1

我有服務,它返回對象的組件,並迭代模板內的對象,一些屬性可能爲空,並打破了js我怎麼能防止這種情況發生?不能迭代對象數組在模板中的打字稿angular2

模板:

<table id="simple-table" class="table table-striped table-bordered table-hover"> 
<caption>Table of artists</caption> 
    <thead> 
     <tr> 
      <th>id</th> 
      <th>name</th> 
      <th>image</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr *ngFor="let artist of artists"> 

      <td>{{artist.id}}</td> 
      <td>{{artist.name}}</td> 
      <td><img class="img-circle" style="width:100%" src="{{artist.images[0].url}}"></td> 
     </tr> 
    </tbody> 
</table> 

artist.images [0]的.url拋出錯誤「未定義的ANNOT讀取屬性‘網址’」,因爲圖片我怎麼能與級聯條件單行修復爲空?

+1

什麼'的console.log(this.artists)'打印,而不是'的console.log(數據)'? – echonax

+0

'

{{artists | json}}
'顯示什麼? –

+0

@echonax它的山姆,我設置了訂閱功能的斷點,並檢查藝術家的財產價值,所有對象加載,沒有任何可疑的看在那裏 – TyForHelpDude

回答

3

您可以使用safe-navigation ?.而不是.,但不能使用[]

這應該工作

artists?.images && artist.images[0]?.url 

或可替代

<table *ngIf="artists.images.length" ...