首页 > 解决方案 > Angular 7 ngFor 迭代对象数组

问题描述

我无法遍历对象数组。在每个对象中,我都有一个名称,但我无法获取对象的文本或其中的名称。

我的 ts 文件中有以下代码

retrieveMultiple(config, "accounts")
.then(
    (results) => {
        const accounts: any[] = [];
        for (let record of results.value) {
            accounts.push(record);
        }

        this.accounts= accounts;
        console.log(accounts[0].name);
        console.log(accounts);
    },
    (error) => {
        console.log(error);
    }

我的 HTML 文件中有这个:

      <p>Accounts:</p>
  <ul>
    <li *ngFor="let account of accounts | json">
      {{ account.name }}
    </li>
  </ul>

标签: angulartypescript

解决方案


你的循环表达式中不应该有json管道。将您的输出代码更改为:

<p>Accounts:</p>
<ul>
  <li *ngFor="let account of accounts">
    {{ account.name }}
  </li>
</ul>

或者为了调试你可以使用这个:

<p>Accounts:</p>
<ul>
  <li *ngFor="let account of accounts">
    {{ account | json }}
  </li>
</ul>

推荐阅读