Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. Here's the snippet of my code:

    app.controller('myCtrl', function($scope, $http) {
     var data = '';
     $http.get("data.json")
       .then(function(response) {
        data = response.data;
     });
     vm.mapOptions = {
        controls: {
            navigator: false
        },
        center: [40, -35],
        zoom: 3,
        layers: [{
            style: {
                fill: {
                    color: '#1996E4'
                },
                stroke: {
                    color: '#FFFFFF'
                }
            },
            type: 'shape',
            dataSource: data
        }],
        shapeCreated: onShapeCreated,
        shapeFeatureCreated: onShapeFeatureCreated
    };
    });

I'm unsure if it's even possible to update a global variable after an HTTP call. Any advice or guidance would be greatly appreciated.

Thank you in advance for your help.

Answer №1

When sending an http request, there is a delay between sending the request and receiving the response, especially when accessing an API on a server. During this time, the execution continues immediately, causing any statements after the http call to execute before the response is received. This can lead to failure if there are dependencies on the response.

In your situation, vm.mapOptions depends on data, which is a local variable storing the response from the get request. So what can you do?

Step 1: Make a function for all code related to handling the response:

$scope.myCallBack = function(data){
  vm.mapOptions = {
    controls: {
        navigator: false
    },
    center: [40, -35],
    zoom: 3,
    layers: [{
        style: {
            fill: {
                color: '#1996E4'
            },
            stroke: {
                color: '#FFFFFF'
            }
        },
        type: 'shape',
        dataSource: data
    }],
    shapeCreated: onShapeCreated,
    shapeFeatureCreated: onShapeFeatureCreated
   };
}

Step 2: Call the myCallBack function within your $http.get right after receiving the response

var data = '';
$http.get("data.json")
  .then(function(response) {
    data = response.data;
    $scope.myCallBack(data);
});

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

Show various error messages depending on the type of error detected

When pulling data from an API, my goal is to handle errors appropriately by displaying custom error messages based on the type of error that occurs. If the response is not okay, I want to throw an error and show its message. However, if there is a network ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...

AngularJS, NodeJS, and Mongoose Challenge in Internet Explorer 11

I am currently working on developing my website using the AngularJS framework for the front end, Node.js for the backend, and Mongoose to store data in a MongoDB database. Everything works fine in Firefox RS v.24 and Chrome - when I add a new user to the ...

Utilizing Angular for enhanced search functionality by sending multiple query parameters

I'm currently facing an issue with setting up a search functionality for the data obtained from an API. The data is being displayed in an Angular Material table, and I have 8 different inputs that serve as filters. Is there a way to add one or more s ...

What could this error be in Chrome console: "Uncaught SyntaxError: Unexpected token ':'"

Why am I getting this error in the Chrome console: "Uncaught SyntaxError: Unexpected token ':'"? I have a JSON file located at the root of my application: <script src="levels.json"></script> Here is the content of my JSON file: { ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

Error in returnTo behavior. The URL is being deleted just before making the post request

I have implemented express-session and included a middleware that assigns the value of req.session.returnTo to the originalUrl. router.post( '/login', passport.authenticate('local', { failureFlash: true, failureRedirect: &ap ...

Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev. However, an issue arises every time Next.js boots up, displaying the following error: FetchError: request to https://fonts.gstatic.com/ ...

Exploring JavaScript capabilities with Google - managing and updating object names with numbers

After importing JSON data into Google Scripts, I am able to access various objects using the code snippet below: var doc = Utilities.jsonParse(txt); For most objects, I can easily retrieve specific properties like this... var date = doc.data1.dateTime; ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

Sending a multitude of variables using strings, evaluating them through various functions, and incorporating a variety of methods

To put it simply, my goal is to utilize an object literal that allows me to pass an unknown quantity of variables in any order to a function. While this may seem straightforward in principle, within my code, this object literal is passed to a second functi ...

Using dynamic template URLs in resolving with Angular's UI-Router can provide flexibility

Currently, I have implemented a parent directive for an entire view to interchange templates based on the outcome of a promise. .directive('myDirective', function(myService) { var rootDir = '/path/to/templates'; return { ...

While attempting to run the project I downloaded from GitHub using the command npm run serve, I encountered the following error: "Syntax Error: Error: No ESLint configuration found in

After receiving a Vue.js project from GitHub, I attempted to download and run it. However, when I tried the command npm run serve, I encountered an error message: Syntax Error: Error: No ESLint configuration found in C:\Users\User\Desktop&bs ...

Transform the v-model value from numerical to textual representation

Currently, I am using the <q-select> component and populating it with options fetched from an API. The issue arises when setting the value as the ID of the object, which is a number while the component expects a string, resulting in an error. <s- ...

Tips for customizing babel's preset plugin configurations

I've integrated babel-preset-react-app into my project with the following .babelrc configuration: { "presets": ["react-app"], "plugins": [ "transform-es2015-modules-commonjs", "transform-async-generator-functions" ] } Currently, I&apos ...

Prevent a HTML button from being clicked multiple times before it disappears (using Django)

I am currently working on a Django project that involves events where users can join by adding their user_id and event_id to the attend model. On the event page, there is a join button form that, when clicked, adds the user to the attendees list. After cli ...