Angular Subscribe and ngOnInit

i am new to angular and trying to write a serice for my user’s UI

i am having a problem of getting data from component.ts to html view.

ngOnInit - i call a serive and save the return object in local variable (this.userData) using subscribe - it loads peroperly but if i try to load this variable outside of subscribe, it just says undefined. i need to get this data outside of subscribe, but always fails in this case.

following is the code

User.service.ts

getUser(id): Observable {
return this.http.get(“http://_apiURL/users/” + id);
}

user.component.ts

ngOnInit() {
this.usrSrvc.getUser(8).subscribe(
(data) => {
this.userData = data;
console.log('services: ', this.userData); // it loads the data and print in console
});
console.log('init: ', this.userData); //at this point i lost all the data
}

You are making an incorrect assumption here. The subscribe block is asynchronous which means the subscription code is not executed until angular has received the subscription being ready. This would usually take some event loops to trigger and would usually be after it has processed the init console log line. Javascript and angular does not wait for the subscribe block to execute before continuing which is something you just have to mentally bend your brain into understanding.

You need to handle in your html for the possibility of this.userdata being undefined for a period until the subscription initialises. The easiest way to do this is to use an *ngIf=“this.userdata” in a div surrounding your html to display your userdata