【问题标题】:retrieve JSON list with absent Object and replace them by null using Angular2使用 Angular2 检索缺少 Object 的 JSON 列表并用 null 替换它们
【发布时间】:2017-05-13 11:55:26
【问题描述】:

这是我的 JSON 数组:

"user" : {
   "id": 456,
   "nickname": "xxx",
   "pf": {
        "id": 123,
        "account": [
            {
                "accountid": 1494235749,
                "status": "New",
                "accountnbr": 12345,
                "cyc": {
                    "cycid": 1494404053,
                    "active": true,
                    "status": "New",
                    "name": "QST192017",
                },

            },
            {
                "accountid": 1494403399,
                "status": "New",
                "accountnbr": 915177,
                "cyc": {
                    "cycleid": 1494406299,
                    "active": true,
                    "status": "Closed",
                    "name": "QSL342014"
                }
            },
            {
                    "accountid": 1494500399,
                    "status": "New",
                    "accountnbr": 90010,
            }
        ]
     },
}

这就是我的模板中的内容:

 <tr *ngFor="let account of accounts">
            <td>{{ account.accountnbr }}</td>
            <td>{{ account.cyc.name}}</td>
 </tr>

我试图检索我所有帐户的列表,并且您可以看到其中一个帐户没有 cyc,并显示错误,知道如何在列表中将缺少的 JSON 对象替换为 null 吗?

PS:我正在使用 angular2

谢谢。

/K

【问题讨论】:

  • 我已经更新了我的问题:目的是显示所有帐户的列表。就是这样。

标签: arrays json angular


【解决方案1】:

使用account.cyc?.name 将解决您的问题。当account 没有cyc 时,您的模板只会显示空白而不会出现任何错误。

请参阅safe-navigation-operator(?) 的文档。

<tr *ngFor="let account of accounts">
  <td>{{ account.accountnbr }}</td>
  <td>{{ account.cyc?.name}}</td>
</tr>

【讨论】:

  • @Pegyy:这是什么意思(?)?
  • @KOul 我添加了文档链接来回答。一句话说:它会在检索之前检查对象是否存在。
【解决方案2】:

这就像使用*ngIf 一样简单:

<div *ngFor="let acc of account">
    <div *ngIf="!acc.cyc">NO CYC ON THIS ACCOUNT</div>
</div>

为此,一个不存在的对象 null/undefined。

您还可以映射组件中的对象并将其设置为 null:

account.map(x =>{
    if(!x.cyc){
        x.cyc = null;
    }
    return x;
});

【讨论】:

  • 感谢 Tyler 的解决方案。它也有效。
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 2013-04-27
  • 2021-04-24
  • 1970-01-01
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 2017-04-11
相关资源
最近更新 更多