javapedia.net
javapedia.net

Reputation: 2731

angular load data from server during ngOnInit not working

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

Answers (1)

Aleš Doganoc
Aleš Doganoc

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

Related Questions