You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 8/9调用在线API无数据显示问题求助

问题排查与修复方案

我帮你定位到了几个关键问题,这就是数据无法渲染的核心原因:

1. 生命周期钩子拼写错误

你的AppComponent里写的是ngOnInt(),但Angular的初始化生命周期钩子正确名称是**ngOnInit()**(注意是Init而非Int)。这个拼写错误直接导致你的API请求代码完全没被执行,自然拿不到后端数据。

修复后的app.component.ts代码片段:

export class AppComponent implements OnInit {
  title = 'angular-apicall';
  constructor(private _freeApiService: FreeapiService) { }

  istComments: Comments[] = []; // 建议初始化空数组,避免模板临时报错
  ngOnInit() { // 修正拼写错误
    this._freeApiService.getComments()
      .subscribe ( data => {
        this.istComments = data;
        console.log('获取到的评论数据:', data); // 新增日志,方便确认数据是否正常返回
      } );
    console.log("组件初始化逻辑已触发");
  }
}

2. 模板语法错误

在app.component.html的最后一列,你写的是{{com.body]}}——这里把闭合的大括号}误写成了方括号]。这个语法错误会导致该行渲染失败,甚至可能影响整个*ngFor循环的执行。

修复后的模板代码片段:

<tr *ngFor="let com of istComments">
  <td>{{com.id}}</td>
  <td>{{com.postId}}</td>
  <td>{{com.name}}</td>
  <td>{{com.email}}</td>
  <td>{{com.body}}</td> <!-- 修正括号错误 -->
</tr>

额外优化建议

给istComments初始化空数组= [],可以避免API请求返回前,*ngFor因为数组为undefined而抛出隐性错误,让页面渲染更稳定。

把这两处问题修复后,刷新页面就能看到评论数据正常渲染到表格里了。

内容的提问来源于stack exchange,提问作者sajid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:17:48