Subscribe to observable is returning undefined

Maybe some pictures help?

The numbers here indicate the order of operations.

Send the Http Request
enter image description here

  1. Component is initialized and calls the getMovies method of the movieService.
  2. The movieService getMovies method returns an Observable. NOT the data at this point.
  3. The component calls subscribe on the returned Observable.
  4. The get request is submitted to the server for processing.
  5. The ngOnInit method is complete.

Any code here after the subscribe cannot access the movies property since the data has not yet been returned.

Receive the Http Response
enter image description here

At some LATER point in time …

  1. The movies are returned to the service.
  2. If the process was successful, the first callback function is executed.
  3. The local movies property is assigned to the movies returned from the service. It is only here that the movies property is finally set.

Attempting to access the movies property prior to step #8 results in an error.

Can we access the value here? NO
enter image description here

To fix it:
enter image description here

Leave a Comment