Reputation: 2731
I am calling the movie data service during startup by calling the subscribe method in ngOnInit. I debugged and see that this.movies array getting populated successfully. However, ngFor in the template is not displaying any data. Could you help me understand what is the issue? may be calling from ngOnInit is a bad idea?
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>
UPDATE(SOLUTION):
asterisk was missing in ngFor directive.
<tr ngFor="let movie of movies; let i =index;">
<td>{{i}}</td>
<td>{{movie| json}}</td>
</tr>
Upvotes: 0
Views: 1654
Reputation: 12052
As it is already pointed out in the comments the problem with your code is that you did not prefix the ngFor
with an asterisk it needs to ne *ngFor
. There is no problem in calling services from OnInit.
I have also created a StackBlitz sample from your code that demonstrates it works.
Upvotes: 1