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

Error: Angular7 Unable to locate namespace 'google'

I am currently utilizing the import { MapsAPILoader } from '@agm/core'; package to enable auto-complete address search functionality. However, I have encountered an error message stating cannot find namespace 'google'. The error occu ...

Only match the character if it is not at the beginning of the line and if another character is not on the

Is there a way to only match the character "=" in a string if it is not at the beginning of a line and no other character, for example "$", appears on the same line? The equal sign should not be at the beginning of a line No other character, such as "$", ...

Retrieving information from a dynamically generated HTML table using PHP

I have successfully implemented functionality using JavaScript to dynamically add new rows to a table. However, I am facing a challenge in accessing the data from these dynamically created rows in PHP for database insertion. Below, you will find the HTML ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the following line of code: chrome_o ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

Using jQuery UI Tabs to Dynamically Select a Tab Based on a Link

Recently, I have been exploring the idea of using a script to open a specific tab: $('.tofour').click(function() { // bind click event to link $tabs.tabs('select', 3); // switch to third tab return false; }); However, my dilem ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: f ...

What is the best way to spin a div HTML layer?

I'm trying to modify a Div layer that looks like this: ... <style type="text/css"> <!-- #newImg { position:absolute; left:180px; top:99px; width:704px; height:387px; z-index:1; background-image:url(../Pictures/rep ...

Encountering an issue when trying to retrieve the "createdAt" property in Cloud Code using the Parse Framework

I am working with Cloude Code to develop a more complex query, but I am having trouble accessing the automatically created "createdAt" property by Parse. Here is my code: Parse.Cloud.define("get_time", function(request, response) { var query = new Par ...

Angular and AngularJS directives work together to indicate events on a line chart

Currently, I am creating a dashboard using AngularJS along with Angularjs-nvd3-directives, mainly focusing on line charts. I am interested in adding markers to the chart for specific events. For instance, if I have a time series data, I want to be able to ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

What are some strategies for exporting methods without resorting to the use of import * as ...?

Imagine having a file structured like this: // HelperFunctions.ts export const dateFormat = 'MM/DD/YYYY'; export const isEmpty = (input: string | null | undefined): boolean => { if (input == null) { return true; } if (!in ...

MongoDB has encountered an issue where it is unable to create the property '_id' on a string

Currently, I am utilizing Node.js and Express on Heroku with the MongoDB addon. The database connection is functioning correctly as data can be successfully stored, but there seems to be an issue with pushing certain types of data. Below is the database c ...

What is the best way to toggle between rendering two components or updating two outlets based on a route in React Router?

There is a React application I am working on that utilizes React-Router. My layout component has the following structure: import React from 'react'; import Header from './components/Header/Header'; import Footer from './components/ ...

Ensure the computed variable is always up-to-date using Firebase in VueJS

After a successful sign-in through Firebase authentication, I need to update a navigation link. The user login changes are managed within the created hook using .onAuthStateChanged() data () { return { user: null, additionaluserinfo: nul ...

Creating a dynamic sidebar menu with clickable submenus through jQuery and CSS for a user-friendly experience

<div id="sidebar" class="sidebar"> <div class="slimScrollDiv" style="position: relative; overflow: hidden; width: auto; height: 100%;"> <div data-scrollbar="true" data-height="100%" data-init="true" style="overflow: hidden; width: a ...

Update your mappings for the city of Istanbul when utilizing both TypeScript and Babel

Currently, I am facing the challenge of generating code coverage for my TypeScript project using remap Istanbul. The issue arises due to the usage of async/await in my code, which TypeScript cannot transpile into ES5 directly. To circumvent this limitation ...

How can I display an array with keys from php in AngularJS using ng-repeat?

I have a rootScope variable that will store product categories, each category may or may not have child categories. Here is how I assign the rootScope: $rootScope.categoryList = $http.get('category').then((result) -> result.data) This code s ...