Angular中ngFor渲染表格无数据,控制台已有数据如何解决?
问题分析与解决方案
核心问题
- 模板中
*ngFor绑定的是invoices数组,但组件始终未给该数组赋值——接口返回的数据被存入了invoice变量,和模板使用的invoices无关联。 - 接口返回的是单个
InvoiceResponse对象,而*ngFor仅能遍历数组,直接使用单个对象会导致渲染失败。 class是JavaScript保留字,模板中直接调用invoice.class可能引发语法冲突。
修复步骤
1. 修正组件数据赋值
将接口返回的单个发票对象包装为数组,赋值给invoices:
export class InsightsComponent implements OnInit { invoice: any; protected invoices: any[] = []; ngOnInit(): void { this.provider.getInvoice(this.firmService.getDomain()) .then(data => { // 将单个对象存入数组,供*ngFor遍历 this.invoices = [data]; }) .catch(err => console.error('获取发票数据失败:', err)); } }
若接口实际返回发票数组(如
InvoiceResponse[]),直接赋值即可:this.invoices = data;,同时需修改FirmProvider的返回类型为PromiseLike<InvoiceResponse[]>。
2. 优化模板中的保留字引用
将模板里的invoice.class改为invoice['class'],规避保留字冲突:
<tbody> <tr *ngFor="let invoice of invoices"> <td>{{ invoice.type }}</td> <td>{{ invoice.title }}</td> <td>{{ invoice.status }}</td> <td>{{ invoice.detail }}</td> <td>{{ invoice['class'] }}</td> <td>{{ invoice.trace }}</td> </tr> </tbody>
3. 简化Provider的Promise写法(可选)
手动封装Promise无必要,直接用RxJS的toPromise()转换Observable,代码更简洁:
export class FirmProvider { constructor(private http: HttpClient) {} getInvoice(invoiceDomain: string): Promise<InvoiceResponse> { const url = `https://${invoiceDomain}.${environment.domain}v1/invoice/`; return this.http.get<InvoiceResponse>(url, {withCredentials: true}).toPromise(); } }
内容的提问来源于stack exchange,提问作者Future Hacker
相关产品推荐
相关产品推荐

