Skip to content Skip to sidebar Skip to footer

Assigning Value To A Variable In Angular Component From A Subscribe Of Observeble Http Request

when I want to assign a value to a local variable in Angular component from subscribing HTTP request I get undefined patient: Patient; hpId: any; ngOnInit() { const id

Solution 1:

There are two ways:

1) If you want to display hdId in HTML page then use like {{ hpId }}

2) If you want to call another API then you can wrap that call inside .subscribe() call like

fetchPatient(id: number) {
    this.patientService.getPatient(id)
    .subscribe( data => {
      this.patient = data;
      this.hpId = this.patient.appointment[0].healthProfessionalId;
      this.yourMethod(this.hdId); // here
    });
}

yourMethod(hdId){
     console.log(hdId);  // do whatever with `hdId`
}

Solution 2:

  • Coding in typescript is like plumbing..you have to code like a stream. If you turn the tap on but if the water is on the way until it reaches the tap there won't be water so if you planned to wash your clothes you have to do it after the water comes from the tap.
  • So when you call the method this.fetchPatient(id); it will hit the back-end and wait in the subscribe until it gets data or error.after the this.fetchPatient(id); then you put your console.log(this.hpId); at this point data is not retrieved but the call was made therefore it will show undefined. if you want to see data put the console log inside subscribe after this line this.hpId = this.patient.appointment[0].healthProfessionalId;
  • Furthermore if you want to use value of this.hpId in other methods call those methods after this.hpId = this.patient.appointment[0].healthProfessionalId; line.

Post a Comment for "Assigning Value To A Variable In Angular Component From A Subscribe Of Observeble Http Request"