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.
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;
});