How to store data sent from an API into a variable in IONIC 4?

Asked

Viewed 79 times

-1

I have a function in Ionic that receives an array from the API and shows the received data

public info;

  async showinfo() {
    await this.authService.getInfo().subscribe(
      data=>{
        this.info = data;
        console.log(data);
        for(let i=0; i<data.length; i++){
          this.info[i];
        }
    },
    error=>{
      console.log(error);
    });

    console.log(this.info); //aparece undefined
 }

When I give a console.log() inside the subscribe I can see the value I get from the API but if I try to see the value outside of it, it doesn’t show the data. How do I see off the subscribe value of the variable??

1 answer

1


This is because you are performing an operation asynchronous. The code outside the subscribe is executed before, so the undefined on console output.

A solution would be to create a method to manipulate the variable info and call it within the Observable inscription. In this way, manipulation occurs after attribution of some value to info

Example:

public info;

async showinfo() {
 await this.authService.getInfo().subscribe(
  data => {
   this.info = data;
   console.log(data);
   for (let i = 0; i < data.length; i++) {
    this.info[i];
   }
   handleInfo();
  },
  error => {
   console.log(error);
  });
}


handleInfo() { // realiza a manipulação de info
 console.log(this.info);
}
  • 1

    thank you very much!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.