0

Using the following service to set result to this.temp, console log shows the result when inside the subscribe, but returns undefined when outside.

   1) this.http.get('../../assets/students.json').subscribe((data)=>{
   2)   this.temp = data;
   3)   console.log(data);//shows result
   4)   console.log(this.temp);//shows result
   5) })
   6) console.log(this.temp);//undefined

but in the console line, 6 is outputted first and then 3 and 4

Omkar Dixit
  • 746
  • 1
  • 9
  • 19
  • 2
    `get` is asynchronous, so order of calls is `1, 6, 2, 3, 4`. Edit: See [here](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular). – Phix Jun 07 '19 at 19:07
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – Igor Jun 07 '19 at 19:12
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/1260204) – Igor Jun 07 '19 at 19:12

1 Answers1

1

This happens as the http call in angular is implemented via observables which will evaluate asycn at a future point of time.Now if you want to do something with the data or this.temp you have to do it inside the subscribe call.

Vishnu
  • 897
  • 6
  • 13