-1

I am calling a dummy web API to populate a variable of class to use it further but then I came across an odd scenario which is confusing me:

export class myClass implements OnInit{ 
    data : any;    
    constructor (private http:HttpClient){}
    ngOnInit(){  
        this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342").subscribe(e=>this.data = e);
        alert("beforeConsole");        
        console.log(this.data);
        var size = Object.keys(this.data).length;
        alert(size); 
    }
} 

Variable data is populating only when i am using alert ( Just for checking). IF I remove alert("beforeConsole"); then console gives me undefined.

I am not able to understand this. Please suggest what's actually going on.

Roger Wang
  • 565
  • 2
  • 12
  • 30
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
  • When do get undefined. Also try to use `console.log` not `alert` to debug your code – Tony Ngo Jul 02 '19 at 09:46
  • 1
    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) – Vikas Jul 02 '19 at 09:48
  • i tried console.log but its gives me as console.log(this.data) gives me undefined if i do not use alert("beforeConsole"); – Passionate Coder Jul 02 '19 at 09:48
  • try this... `ngOnInit(){ this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342").subscribe( e=> {this.data = e; alert("beforeConsole"); console.log(this.data); var size = Object.keys(this.data).length; } () => {alert(size);} ); }` – Akber Iqbal Jul 02 '19 at 09:48
  • Possible duplicate of [Unable to load data inside ngOnInit](https://stackoverflow.com/questions/54519854/unable-to-load-data-inside-ngoninit) – SiddAjmera Jul 02 '19 at 09:49

2 Answers2

0

Http.get returns an Observable and is asynchronous. Your console.log runs before the request has time to process.

Move your console.log inside your subscribe as this will run once the observable is emitted.

this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342")
   .subscribe(e => { 
     this.data = e;
     console.log(this.data);
     var size = Object.keys(this.data).length;
   });
  • 1
    There are enough answers to such questions already in here. Instead of answering the question, please consider marking it as duplicate. This would help make StackOverflow less polluted. Thanks :) – SiddAjmera Jul 02 '19 at 09:51
-1

I suggest You to use async await.

ngOnInit(): void { this.initialize(); }

async initialize(): Promise<void> {
  try {
    this.data = await this.http.get("http://dummy.restapiexample.com/api/v1/employee/82342").toPromise();
    console.log(this.data);
  } catch (e) { console.error(e); }
}
PierreD
  • 860
  • 1
  • 14
  • 30