seesharp
seesharp

Reputation: 101

Why is my Angular code not printing/running sequentially?

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:

(Expectation) But I expected the name to print first, then the "NgOnInit AFTER"

Upvotes: 1

Views: 516

Answers (1)

Cyril
Cyril

Reputation: 254

this.http.get is an async call. the http request is sent before your first log then the printNames method finishes so you have your first log and then you receive the http response so the code in the subscribe method is executed (including the createForm method with the 2 logs).

Upvotes: 2

Related Questions