无法在打字稿angular2的组件模板中迭代对象数组

cant iterate object array in template of component in typescript angular2

我有 return 对象到组件的服务,并在模板中迭代对象,一些属性可能为 null 并破坏了 js 我如何才能防止这种情况发生?

模板:

<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 read property 'url' of undefined" 错误,因为图像为 null 我如何在具有级联条件的单行中修复?

您可以安全导航 ?. 而不是 . 但不能使用 [].

这应该有效

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

或者

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