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

Hello… I had exactly same problem but I need to populate some dropdowns in automatic based on Lists
filtered in cascade… I understand what was explained, but in my scenario I do need to make usage of this properties assigned inside subscribe method somewhere in the code to refilted my lists, so, when the app loads, it t be able to populate the infomration in my dropdowns already filtered.

In other words, based on mehhfooz question, If we cannot user this.userData inside ngOnInit method and neither inside subscribe, where will be the right place to make usage of this.userData outside subscribe method and more important, before the app ends loading.

Hi again… well I solved it by making use of the property just inside the subscribe method.


        this.categoryListFiltered =
          this.categorySCRList
            .filter((x) => x.creditClassId === inProgressForm.creditClassId)
            .sort((a, b) => a.sortOrder - b.sortOrder);