Trying to understand why some lines of code are run before others, even though they are not written in that order.
I see in the following SO article they are suggesting Promises:
Sequential code execution in angular/ typescript
Is this recommended here, and more importantly, Why? I'm not understanding the Why from that article; it focuses more so the how.
I tried looking into js single threading, promises, observables, etc. I've also been going through a tutorial and it talks about components, modules, databinding, directives, etc but not understanding the Why.
ngOnInit() {
this.printNames(); //Gets info from database and creates a reactive form , then prints values to console
console.log("NgOnInit AFTER printNames()..");
}
printNames() {
this.GetUserInfoFromDB(userID.subscribe(result => {
this.dbt = result;
this.createForm();
}
createForm() {
this.profileForm = this.formbuilder.group({
'firstName': [this.dbt.firstName],
'lastName': [this.dbt.lastName],
});
console.log(this.profileForm.controls["firstName"].value);
console.log(this.profileForm.controls["lastName"].value);
}
-
GetUserInfoFromDB(userID: string) Observable<AProfile> {
let url = URL + '/GetUserInfo';
let Params = new HttpParams();
Params = Params.append('userID' userId);
return this.http.get<AProfile>(url, {params: Params}).pipe(
catchError(this.handleError);
}
(Actual result) Console shows:
"NgOnInit AFTER printNames().."
"John"
"Smith"
(Expectation) But I expected the name to print first, then the "NgOnInit AFTER"