Angular使用ngFor展示嵌套JSON对象时的显示及遍历报错问题
解决Angular ngFor遍历嵌套区块链API数据的问题
你遇到的核心问题是没准确识别API返回的数据结构——尤其是prev_out是单个对象而非数组,同时直接插值复杂类型会触发[object Object]的显示问题。我们一步步来修复:
1. 先明确API返回的数据结构
从目标地址返回的结果来看:
txs是交易数组,每个交易对象包含:inputs: 输入项数组,每一项是一个对象out: 输出项数组,每一项是一个对象- 每个
input里的prev_out是单个对象(不是数组),包含addr、value等属性
2. 修复[object Object]的显示问题
当你直接插值{{t.inputs}}或{{t.out}}时,Angular会调用对象的toString()方法,自然会显示[object Object]。你需要遍历这些数组,取出具体属性值展示。
3. 修复NgFor不能遍历对象的错误
你之前尝试用*ngFor="let out of field.prev_out",但prev_out是对象不是数组,而ngFor仅支持遍历可迭代对象(比如数组),所以触发了Cannot find a differ supporting object错误。对于对象,要么直接访问其属性,要么用keyvalue管道遍历所有键值对。
正确的实现代码
第一步:优化Component代码(定义类型,避免any)
先给交易数据定义接口,让代码更清晰,同时获得类型提示:
// 定义数据接口,匹配API返回结构 interface TransactionOutput { addr: string; value: number; // 可添加其他需要的属性 } interface TransactionInput { sequence: number; witness: string; prev_out: TransactionOutput; // 可添加其他需要的属性 } interface Transaction { txid: string; inputs: TransactionInput[]; out: TransactionOutput[]; // 可添加其他需要的属性 } export class InputComponent implements OnInit { address = "3MvuMn4CESuvA89bfA1cT8mgC4JtKaReku"; transactions: Transaction[] = []; // 用定义好的接口代替any constructor(private blockchain: BlockchainService) { } ngOnInit() { this.getTransactions(); // 初始化时直接获取交易 } submit(){ console.log(this.address); } getTransactions(){ this.blockchain.getTransactions().subscribe((data) => { this.transactions = data["txs"]; console.log('交易数据:', this.transactions); // 注意:this.transactions是数组,所以this.transactions['inputs']会返回undefined,要访问单个交易的inputs需用this.transactions[0].inputs }); } }
第二步:正确的HTML模板
遍历交易数组,再分别遍历每个交易的inputs和out数组,直接访问prev_out的属性(因为它是单个对象):
<div *ngFor="let tx of transactions" class="transaction-container"> <mat-card class="example-card"> <mat-card-header> <mat-card-title>交易哈希: {{ tx.txid }}</mat-card-title> </mat-card-header> <mat-card-content> <!-- 交易输入区域 --> <h3>交易输入</h3> <table class="table"> <thead> <tr> <th>来源地址</th> <th>Sequence</th> <th>Witness</th> </tr> </thead> <tbody> <tr *ngFor="let input of tx.inputs"> <td>{{ input.prev_out.addr }}</td> <td>{{ input.sequence }}</td> <td>{{ input.witness }}</td> </tr> </tbody> </table> <!-- 交易输出区域 --> <h3>交易输出</h3> <table class="table"> <thead> <tr> <th>接收地址</th> <th>金额(聪)</th> </tr> </thead> <tbody> <tr *ngFor="let output of tx.out"> <td>{{ output.addr }}</td> <td>{{ output.value }}</td> </tr> </tbody> </table> </mat-card-content> </mat-card> </div>
额外技巧:遍历对象的所有属性
如果未来遇到需要遍历对象全部键值对的场景(比如prev_out有未知属性),可以用Angular的keyvalue管道:
<div *ngFor="let item of input.prev_out | keyvalue"> {{ item.key }}: {{ item.value }} </div>
内容的提问来源于stack exchange,提问作者iloveStackOverflow
相关产品推荐
相关产品推荐

