angular - ngOnInit 期间来自服务器的角度负载数据不起作用
问题描述
我在启动期间通过调用 ngOnInit 中的 subscribe 方法来调用电影数据服务。我调试并看到 this.movies 数组已成功填充。但是,模板中的 ngFor 不显示任何数据。你能帮我理解是什么问题吗?可能从 ngOnInit 调用是个坏主意?
现在运行的.component.ts
@Component({
selector: 'app-now-running',
templateUrl: './now-running.component.html',
styleUrls: ['./now-running.component.css']
})
export class NowRunningComponent implements OnInit {
constructor(private nowrunningService: NowRunningServiceService) { }
movies: Array<Movie>=[];
ngOnInit() {
console.log("MOvies length"+ this.movies);
this.nowrunningService.getNowRunningMovies().subscribe((data:any) => {
// this.movies= data.results;
data.results.forEach(element => {
this.movies.push(new Movie(element.title))
});
console.log(this.movies);
console.log("MOvies length"+ this.movies.length)
});
}
}
现在运行.component.html
<table>
<tr ngFor="let movie of movies; let i =index;">
<td>{{i}}</td>
<td>{{movie| json}}</td>
</tr>
</table>
app.component.html
<app-now-running></app-now-running>
更新(解决方案):
ngFor 指令中缺少星号。
<tr ngFor="let movie of movies; let i =index;">
<td>{{i}}</td>
<td>{{movie| json}}</td>
</tr>
解决方案
正如评论中已经指出的那样,您的代码的问题是您没有在 the 前面ngFor
加上它需要的星号 ne *ngFor
。从 OnInit 调用服务没有问题。
我还从您的代码中创建了一个StackBlitz 示例来演示它的工作原理。
推荐阅读
- python - Windows Python:sphinx-build.exe 文件“消失”
- android - 无法使用 kotlin 多平台启动前台服务
- pandas - 如何对熊猫中的相邻值组进行编号?
- javascript - 使用 NodeJS 更新 Mongo DB 集合
- r - 如何绘制广义加法模型的样条曲线?
- python-3.x - 如何将输入字符限制为字母
- r - 将具有不规则时间点(不是日期)的向量转换为 R 时间序列对象
- javascript - 如何访问“获取”功能之外的结果?
- javascript - 如何从 Ajax 响应中访问表元素(来自 mysql db)
- android - Android - 矩形下方的阴影效果