1

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 = +this.route.snapshot.paramMap.get('id');
    this.fetchPatient(id);
    console.log(this.hpId);
  }
  fetchPatient(id: number) {
    this.patientService.getPatient(id)
    .subscribe( data => {
      this.patient = data;
      this.hpId = this.patient.appointment[0].healthProfessionalId;
    });
  }
}

I want to use the value of hpId out of the scope of subscribing method

Ayman Safi
  • 77
  • 1
  • 11
  • The value of `hpId` is undefined when the component initializes. You have to put the console log inside the `fetchPatient` subscription. – callback Dec 23 '18 at 15:26
  • @Ayaman Safi But that will be undefined until you get it from your HTTP call. It will give you undefined always as it will be executed before your HTTP call completes – nikhil mehta Dec 23 '18 at 15:26
  • 1
    Your code is all good, if you try to console inside `subscribe` you will see the value. The reason you are seeing it as undefined is because of asynchronous behavior. – Amit Chigadani Dec 23 '18 at 15:27
  • Do you want to display that Id in HTML? – Prashant Pimpale Dec 23 '18 at 15:37
  • use the `| async` pipe if you are displaying it inside the template – quirimmo Dec 23 '18 at 15:38

2 Answers2

2

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`
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
1
  • 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.
umesh99
  • 215
  • 1
  • 11