0

I'm trying to assign the returned array from the server in withing the subscribe method. The problem I'm facing is that after I assign the array it shows as undefined if I console log it. However, if I console log it inside the subscription method it shows all elements.

Is there something that I'm missing?

Here is my code:

export class GetMoviesComponent implements OnInit {

  movies: Movie[];
  constructor(private movieService: MovieServiceService) {
  }

  ngOnInit() {
    this.movieService.getMovies().subscribe((data: Movie[])
      => {
      this.movies = data;

    });

    this.lol();
  }
  lol() {
    console.log(this.movies);
  }

}

And below is my service that calls the API

getMovies(): Observable<Movie[]> {
  return this.http.get<Movie[]>(this.baseUrl + 'getmovies');
}
see sharper
  • 11,505
  • 8
  • 46
  • 65
Csibi Norbert
  • 780
  • 1
  • 11
  • 35
  • 2
    Of course it's undefined. You call lol() immediately after you've sent the request. If you want to print the response, you need to print it when it's received, i.e. from **inside** the subscribe callback. – JB Nizet Jan 12 '20 at 23:35
  • Could you please show how the data coming from the server would be assigned to that array created in the component and used in the HTML? – Csibi Norbert Jan 12 '20 at 23:36
  • You already assign the data correctly. You can see it if you call `this.lol()` just after assigning the data. In your code, you call it outside of the callback. – ConnorsFan Jan 13 '20 at 00:06

0 Answers0