Angular技术问询:如何用API数据填充表格?为何数据变量为空?
问题分析与解决
为什么this.data是空数组
HTTP请求属于异步操作,你当前的代码里,在constructor中调用this.display(this.data)时,this.cinema.getData().subscribe(...)里的回调函数还没执行(API请求还未返回数据),所以此时this.data还是你初始化的空数组。
修正代码
把display方法的调用放到subscribe的回调内部,确保数据返回并完成赋值后再执行相关逻辑:
import { Component } from '@angular/core'; import { CinemaService } from './services/cinema.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ title = 'movie-app'; data: any = []; constructor(private cinema: CinemaService) { this.cinema.getData().subscribe(movies => { console.log(movies); this.data = movies; this.display(this.data); // 数据赋值后再调用方法 }); } display(thing: any) { console.log(this.data); } }
更规范的写法是实现OnInit接口,在ngOnInit钩子中发起请求(Angular推荐不在构造函数中处理业务逻辑):
import { Component, OnInit } from '@angular/core'; import { CinemaService } from './services/cinema.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'movie-app'; data: any = []; constructor(private cinema: CinemaService) {} ngOnInit(): void { this.cinema.getData().subscribe(movies => { console.log(movies); this.data = movies; this.display(this.data); }); } display(thing: any) { console.log(this.data); } }
用API数据填充表格
在app.component.html中通过*ngFor循环渲染表格内容:
<table border="1"> <thead> <tr> <!-- 根据API返回的实际字段定义表头,示例用电影名称、上映时间 --> <th>电影名称</th> <th>上映时间</th> </tr> </thead> <tbody> <!-- 遍历data数组生成表格行 --> <tr *ngFor="let movie of data"> <td>{{ movie.title }}</td> <td>{{ movie.releaseDate }}</td> </tr> </tbody> </table>
注意将movie.title、movie.releaseDate替换为你API返回的真实字段名。
内容的提问来源于stack exchange,提问作者Bishibro
相关产品推荐
相关产品推荐

