``Implementing a method to save the output of an asynchronous request in a global variable for future manipulation

It's been a week and I still can't figure this out. Being new to front-end development, I'm struggling with storing the response from subscribe in a global variable for future use.

ngOnInit(): void {
this.http.get<APIResponse>('url' + globals.applicationId, { headers: httpHeaders })
      .pipe(map((res: APIResponse) => res))
      .subscribe(res => {

        // Storing apiresponse globally
        this.apiresponse = res;

        console.log(this.apiresponse); // This prints what I need

      });

      console.log(this.apiresponse); // This prints undefined
}

I know similar questions might have been asked before, but I couldn't find a solution that fits my specific case. Can someone please assist me without closing or marking this question as a duplicate? Thank you!

Answer №1

The subscribe block executes after the console.log printing undefined. This timing discrepancy is a result of the asynchronous behavior of the get call.

In essence, everything is functioning according to plan.

Answer №2

The data from the API Response is being stored in a global variable named this.apiresponse according to your requirements.

The issue lies in how you are confirming this behavior.

It is important to understand how JavaScript code runs, how asynchronous calls function, and when callbacks are executed.

In this scenario:

The callback function for the subscription will run once the GET API call is finished (once the response comes back from the Backend Server). Since JavaScript does not wait for this call to complete, it continues executing code outside of the subscription(). When the API call is successful, it triggers the subscription callback function and executes it. This explains why the first console.log() inside the subscription block prints the correct value, while the one outside the subscription block does not - at the time it ran, the API call was not complete, so the data was not available yet.

To work on the data, consider calling a function inside the subscription block. I hope this explanation helps!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automating Indesign with HTML5 and JavaScript through IDML files

I am currently working on automating IDML files. My goal is to display an IDML template in an HTML5 editor. Within the sample.idml file, I have a basic TextFrame containing the text "Hello World." After unzipping the file and navigating to the stories fol ...

Best Practices for Angular and Managing Database Access

By now, I have a good understanding that angular.js is a client-side framework, which means any database communication involves sending requests to a server-side script on the server using methods like get/post (with node, php, asp.net, or other technologi ...

Set up an array data by extracting values from an array prop within a Vue component

Within my Vue component, I am dealing with an array prop called selectedSuppliers that consists of objects. My goal is to set up a data property named suppliers and initialize it with the values from selectedSuppliers. However, I do not want any modificati ...

using VueJS, learn how to dynamically apply text to a data variable based on certain props

I'm facing an issue with conditional value assignment to the data variable based on props. The ternary operator is causing errors in my code. Here's a snippet for reference: <template> <div class="absolute left-3 top-1/2"> ...

Is there a variance in window.innerWidth between Chrome and Firefox?

body, html { position:absolute; width:100%; height:100%; margin: 0; padding: 0; overflow: hidden; } When using window.innerWidth, there is a discrepancy between the values returned by Firefox and Chrome. Firefox return ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

The trouble with dynamicHelpers in Nodejs Express

Trying to make my app run smoothly, I've set up the following configurations: app.configure(function(){ app.set('views', __dirname + '/views'); app.enable('jsonp callback'); app.set('view engine', 'j ...

In Rxjs, Subscribe now emits individual items one at a time instead of emitting a list all at once

I've encountered an issue in my Angular 4 application while working with Rxjs and I can't seem to figure out the behavior. Here's a snippet of my code: this.server.get("incidents") //http get resource .flatMap((res) => res.value) //the ...

Changes to the className of a React component will trigger a re-render of

When the className of the parent changes, React children will re-render. import React from 'react'; import { useSelector } from 'react-redux'; import items from './ItemsList.js'; import Item from './Item'; import &ap ...

Excessive loading time for bundle.js production in Angular2

Currently, I'm utilizing angular2 in my project. The following command was used to generate the build. ng build --prod The size of Bundle.js is 1.4MB. In my application, I have integrated angular2-google-maps, bootstrap, and dropzone. Are there an ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...

Accessing properties within nested objects in a class

In my Angular 7 application, I have two object classes filled with data - employee and company (data retrieved through a web API from a database). The Employee class has fields - emp_id, name, surname, and a company object. The Company class has - c_id, ...

Error: Reference 'ref' is undefined in the 'no-undef' context. I am interested in experimenting with loading images from Firebase storage

While working with React, I encountered an issue when trying to fetch an image URL from Firebase Storage and display the image. The error 'ref' is not defined (no-undef) occurred. https://firebase.google.com/docs/storage/web/create-reference Th ...

Display the React component following a redirect in a Next.js application that utilizes server-side rendering

Just starting out with next.js and encountering a problem that I can't seem to solve. I have some static links that are redirecting to search.tsx under the pages folder. Current behavior: When clicking on any of the links, it waits for the API respo ...

Angular/NestJS user roles and authentication through JWT tokens

I am encountering difficulties in retrieving the user's role from the JWT token. It seems to be functioning properly for the ID but not for the role. Here is my guard: if (this.jwtService.isTokenExpired() || !this.authService.isAuthenticated()) { ...

Issue: [unresolved] Provider not recognized: $resourseProvider <- $resourse <- Phone Angular factory

I'm encountering an issue with injecting a resource. Error: [$injector:unpr] Unknown provider: $resourseProvider <- $resourse <- Phone Here is my code: index.html <script src="bower_components/angular/angular.js"></script> < ...

Converting lengthy timestamp for year extraction in TypeScript

I am facing a challenge with extracting the year from a date of birth value stored as a long in an object retrieved from the backend. I am using Angular 4 (TypeScript) for the frontend and I would like to convert this long value into a Date object in order ...

Navigating through Angular JS validation procedures step by step

I have a wizard in angular js consisting of multiple steps: <wizard on-before-step-change="log(event)" on-step-changing="log(event)" on-after-step-change="log(event)" user="user"> <step title="step 1"> </step> <step title="step 2"& ...

"Enhance Your Smart Contract Interaction with Algrand's Method Calling

Currently, I am working on integrating an Algorand smart contract with a Next.js application. To sign transactions, I am utilizing Pera wallet. However, I have encountered an issue when attempting to call methods from the contract on the front end using th ...

Stopping halfway through a jQuery toggle width animation to close again

Perhaps the question may be a bit unclear, but allow me to provide an example. When repeatedly clicking the button that toggles the width, the div continues to animate long after the button press, which is not visually appealing. My desired outcome is for ...