简体   繁体   中英

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

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);
      });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM