无法在typescript angular2中的组件模板中迭代对象数组

时间:2016-12-02 10:06:23

标签: angular typescript2.0

我有服务将对象返回到组件,并迭代模板内的对象,一些属性可能为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抛出&#34; annot read property&#39; url&#39;未定义&#34;错误,因为图像为空如何在级联条件的单行中修复?

1 个答案:

答案 0 :(得分:3)

您可以安全导航.而不是[],而不能导航artists?.images && artist.images[0]?.url

这应该有效

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

或者

<html>
<body>
    <div>
        <p>Coins: @Model.Coins</p>
        <button type="button" id="btnScore"
                onclick="IncrementCount()">Click me!</button>
    </div>
</body>

<script>
function IncrementCount() {
    $.ajax({
        type: "POST",
        url: "/Clicker/IncrementCount",       
        async: true,
        success: function (msg) {
            ServiceSucceeded(msg);
        },
        error: function () {
            return "error";
        }
    });
}
</script>

</html>