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)
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)
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);
})