我有一个简单的REST服务返回类似于以下内容的JSON:
{"id":123,
"name":"Sam",
"transactions":[
{"date":"2018-05-31","amount":29.99,"desc":"shirt"},
{"date":"2018-05-31","amount":42.99,"desc":"pants"},
{"date":"2018-05-31","amount":59.99,"desc":"shoes"}
]
}
我正在尝试在 Angular 组件 (.ts( 中引用它来处理数据。 我能够使用以下方法在 html 模板中很好地阅读它:
<tr *ngFor="let transaction of accountTransactions.transactions ">
<td> {{ transaction.date}} </td>
<td> {{ transaction.amount}} </td>
<td> {{ transaction.desc}} </td>
</tr>
当我在我的组件中时,从 promise 收到值后,我可以访问返回数据的"main"属性(id 和 name(,但我无法弄清楚获取数组中数据的语法或方法:
public getAccountTransactions() {
this.apiService.getAccountTransactions(this.acct).toPromise().then(data => {
console.log('in getAccountTransactions');
this.accountTransactions = data;
console.log(data.id); // this works fine
console.log(this.accountTransactions.id) // this works fine
console.log(this.accountTransactions.transactions[0].amount) // this doesn't work
}
任何帮助将不胜感激。 谢谢。
实际上你的代码没有任何问题。您应该检查 apiService 以查看是否有问题。
在 JSON 中的普通对象中,您实际上没有什么特别的事情要做。 事务[0] 只是在您的对象中丢失