首页 > 解决方案 > ngOnInit 期间来自服务器的角度负载数据不起作用

问题描述

我在启动期间通过调用 ngOnInit 中的 subscribe 方法来调用电影数据服务。我调试并看到 this.movi​​es 数组已成功填充。但是,模板中的 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>

标签: angulartypescript

解决方案


正如评论中已经指出的那样,您的代码的问题是您没有在 the 前面ngFor加上它需要的星号 ne *ngFor。从 OnInit 调用服务没有问题。

我还从您的代码中创建了一个StackBlitz 示例来演示它的工作原理。


推荐阅读