【问题标题】:angular load data from server during ngOnInit not workingngOnInit 期间来自服务器的角度负载数据不起作用
【发布时间】:2019-03-31 00:17:26
【问题描述】:

我在启动期间通过调用 ngOnInit 中的 subscribe 方法来调用电影数据服务。我调试并看到 this.movi​​es 数组已成功填充。但是,模板中的 ngFor 不显示任何数据。你能帮我理解是什么问题吗?可能从 ngOnInit 调用是个坏主意?

now-running.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)

    });

  }

}

now-running.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>

【问题讨论】:

  • ngFor 必须以* 为前缀,即*ngFor="..."
  • 哎呀。是的,谢谢你的发现,不知何故错过了。

标签: angular typescript


【解决方案1】:

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

我还从您的代码中创建了一个 StackBlitz sample 来证明它的工作原理。

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 2018-07-18
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多