Subscribe to observable is returning undefined

Sam Kelham picture Sam Kelham · Oct 16, 2017 · Viewed 33.5k times · Source

So I am trying to subscribe to a simple service that return data from a local JSON file.

I have managed to get the service working, I can log it out in the function, but when I subscribe to the service in the angular 2 component, it is always undefined. I'm not sure why? Any help would be much appreciated.

API service

export class ApiService {
   public data: any;

   constructor(private _http: Http) {
   }

   getData(): any {
       return this._http.get('api.json').map((response: Response) => { 
       console.log('in response', response.json()); //This logs the Object
       this.data = response.json();
       return this.data;
   })
   .catch(this.handleError);
   }
}

Component

export class AppComponent {
   public data: any
   public informationData;

   constructor(private _api: ApiService) {}

   public ngOnInit(): void {
      console.log(this.getDataFromService()); // This return undefined
   }

   public getDataFromService() {
      this._api.getData().subscribe(response => {
          this.informationData = response;
          return this.informationData;
      });
   }
}

Answer

DeborahK picture DeborahK · Oct 17, 2017

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