I am stuck since 1 week and can’t get this working properly. Yes i am new to everything on front-end so please bare with me –
I am trying to store the response from subscribe to global variable for further processing –
ngOnInit(): void {
this.http.get<APIResponse>('url' + globals.applicationId, { headers: httpHeaders })
.pipe(map((res: APIResponse) => res))
.subscribe(res => {
//setting apiresponse for global usage
this.apiresponse = res;
console.log(this.apiresponse); //prints what i want
});
console.log(this.apiresponse); //prints undefined
}
I understand that for SO community this is probably the question that has been asked trillion times but i saw many post with different use cases and not a single response i could find with proper implementation hence i am here seeking help. I would appreciate if someone can help me without marking this question closed or duplicate. Thank you in advance
2
Answers
Your
console.log
that printsundefined
is run before the one inside thesubscribe
block. This is due to the asynchronous nature of the call to get.In short, it work’s as designed.
The API Response Data in the global variable
this.apiresponse
is stored as you want it to be.The issue is how you are verifying this behavior.
You need to be aware of how JS code executes, how
async call
works, and most importantly whencallbacks
are executed.In this case:
The Subscription callback function executes when the GET API call is complete (Response is returned from the Backend Server) and as Javascript does not wait for this call to get complete, the Javascript engine continues to execute the code outside the
subscription()
and when API call is successful, it triggers subscription callback function and executes that. So, The firstconsole.log()
(Inside subscription block) in your case is executed after theconsole.log()
outside subscription blockThis is why
console.log()
inside the subscription block prints the correct value butconsole.log()
outside the subscription block does not as at the time it was executed API was not complete hence data was not present.You can call a function inside the subscription block to work on the data. Hope this helps!