Search code examples
angularjsangular-promiseangularjs-service

value is using before it assigns after the server call


value is using before it assigns after the server call

/** * Consume patient info from cas service. */

 getPatientInfo(event: any, affectType:string) {
    this.patientInfo= new PatientModel();
    let headers = new Headers();
    let estCode = localStorage.getItem(AppUtils.DEFAULT_INSTITUTE); // Logged in user default institute
    headers.append('Content-Type', 'application/json');
    this.masterDataService.getPatientInfo(event).subscribe(result =>{this.patientInfo = result,   console.log("1 "+JSON.stringify(this.patientInfo));
    });
    console.log("2"+JSON.stringify(this.patientInfo));
    this.addPerson(affectType);
}

Here console message 1 displays the result, where messgae 2 return {} string.

console message is like

2 {}
1 {"address":null,"categoryCode":0}

How can I make the statement following the serer call to wait in angular2


Solution

  • since javascript is asynchronous it does not wait until the observable subscribed to an event. it keeps on executing. that is why 2nd console get printed first.

    one thing you can do is create a function and call it inside the subscribe so that it will execute after the result is resolved.

    getPatientInfo(event: any, affectType:string) {
          this.patientInfo= new PatientModel();
          let headers = new Headers();
          let estCode = localStorage.getItem(AppUtils.DEFAULT_INSTITUTE); // Logged in user default institute
          headers.append('Content-Type', 'application/json');
    
          this.masterDataService.getPatientInfo(event).subscribe(result =>{this.patientInfo = result,   console.log("1 "+JSON.stringify(this.patientInfo));
            console.log("2"+JSON.stringify(this.patientInfo));
            this.addPerson(affectType);
          });
    }