skip to Main Content

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


  1. Your console.log that prints undefined is run before the one inside the subscribe block. This is due to the asynchronous nature of the call to get.

    In short, it work’s as designed.

    Login or Signup to reply.
  2. 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 when callbacks 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 first console.log() (Inside subscription block) in your case is executed after the console.log() outside subscription block
    This is why console.log() inside the subscription block prints the correct value but console.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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search