0

I am using Angular framework and API service to receive data from a table from my database.

My purpose is to fill a JSON with the data received with my apiService.getData() and my subscribe() functions.

When i do

console.log(this.observance)

inside the subscribe(), it displays all my table, as it is supposed to do.

But when I do

console.log(this.observance)

just after the subscribe(), in the last line, my console says that my variable this.observance is 'undefined'. Do you know why? Thanks! (sorry for my bad English)

Here is my code:

this.apiService.getData("observance/patient/" + this.patient.id).subscribe(
      x => {
        this.observance = JSON.parse(x.body);
      },
      err => {
        console.log(this.observance);
        console.log("Aucune observance récupéré.");
      },
      () => console.log(this.observance)
    )
    console.log(this.observance);
Gaël J
  • 11,274
  • 4
  • 17
  • 32
Jul
  • 1

2 Answers2

0

I'd recommend reading about Observables and asynchronous programming.

In your code, you are basically saying:

  • call apiService.getData(...) and when the response is received (in the future, likely in few milliseconds) do something: parse response and store it in observance then log its value
  • log observance value (immediately)

The important thing here is that the subscribe() method on Observable will return immediately and your last console.log will get executed immediately before the code defined in the subscribe parameters is executed.

You should see it by yourself by adding some more console.log like:

this.apiService.getData("observance/patient/" + this.patient.id).subscribe(
      x => {
        console.log("This is called when receiving success response");  
        this.observance = JSON.parse(x.body);
      },
      err => {
        console.log("This is called when receiving error response");  
        console.log(this.observance);
        console.log("Aucune observance récupéré.");
      },
      () => {
        console.log("This is called after response handling");  
        console.log(this.observance)
      }
    );
console.log("This is called right after subscription");
console.log(this.observance);
Gaël J
  • 11,274
  • 4
  • 17
  • 32
0

On the one hand, the getData function from the apiService is an asynchronous function. Then, when you subscribe to this, the code inside the subscribe is executed after the data is returned from the api. For this reason, the first console.log sentence works as you expected. On the other hand, as I mentioned above, the getData function is asynchronous, which implies that the next sentence (console.log(this.observance);) is executed without waits that the getData function ends. Then, when the console.log is executed the data is not retrieved from the API yet.