0

How to return a value with subscribe?

I tried to create a global variable, but I did not succeed.

this.postServices.getData().subscribe((res)=>{
                this.data = res
          })

console.log(this.data)
marcelo.delta
  • 2,730
  • 5
  • 36
  • 71

1 Answers1

4

The first part starts an asynchronous operation, and the console.log part is run immediately, before the async operation finishes.

You have to delay the reference to this.data until you know the async operation has completed.

You can do that by putting the console.log inside the subscribe handler:

this.postServices.getData().subscribe((res)=>{
  this.data = res;
  console.log(this.data);
})
Aviad P.
  • 32,036
  • 14
  • 103
  • 124