"AngularJS waits for the initial JSON data to load before rendering

I am struggling to retrieve certain information in advance. Specifically, I need to access a variable called var myId and pass it to myapp.run(). In my setup, there are 2 controllers each handling different pages.

var myId; // This variable is crucial
afroEarthApp.controller('afroEarthMainCtrl',['$scope','$http','$location','$cookies', '$rootScope', function($scope, $http, $location, $cookies, $rootScope) {
    $http.get('js/afro.json').success(function(data) {
        $scope.myDataFirst = data;
        $scope.singleNiche = $scope.myDataFirst.US;
        $rootScope.header = $scope.singleNiche;
        $rootScope.myDataVar = $scope.myDataFirst.US;
    });
    $scope.setCountry = function (choise) {
        switch (choise){
            case "US" : $scope.singleNiche = $scope.myDataFirst.US;
                break;
            case "UK" : $scope.singleNiche = $scope.myDataFirst.UK;
                break;
            case "SA" : $scope.singleNiche = $scope.myDataFirst.SA;
                break;
            case "CAN" : $scope.singleNiche = $scope.myDataFirst.CAN;
                break;
            case "AU" : $scope.singleNiche = $scope.myDataFirst.AU;
                break;
        }
        $cookies.put("myCountry", choise);
        $rootScope.header = $scope.singleNiche;
    };
    $rootScope.bodylayout = "home-page";
    myId = $scope.singleNiche // assigning here
}]);
afroEarthApp.controller('SingleCtrl',['$scope','$http', '$location', '$routeParams', 'Single', '$cookies', '$rootScope', function($scope, $http, $location, $routeParams, Single, $cookies, $rootScope) {
  $scope.niche = $routeParams.niche;
    $rootScope.bodylayout = "single-page";
    var url = 'sites/'+$routeParams.niche+'.json';
    Single.get({niche: $routeParams.niche}, function (data) {
        $scope.singleFirst = data;
        $scope.singleNiche = $scope.singleFirst.US;
        var getCountry = String($cookies.get("myCountry"));
        $scope.setCountry = function (choice) {
            switch (choice) {
                case "US" :
                    $scope.singleNiche = $scope.singleFirst.US;
                    break;
                case "UK" :
                    $scope.singleNiche = $scope.singleFirst.UK;
                    break;
                case "SA" :
                    $scope.singleNiche = $scope.singleFirst.SA;
                    break;
                case "CAN" :
                    $scope.singleNiche = $scope.singleFirst.CAN;
                    break;
                case "AU" :
                    $scope.singleNiche = $scope.singleFirst.AU;
                    break;
            }
            $rootScope.header = $scope.singleNiche;
        }
        $scope.setCountry(getCountry);

    })
    $rootScope.header = $scope.singleNiche;
    myId = $scope.singleNiche; //assigning here
}]);
afroEarthApp.run(function ($rootScope) {
    $rootScope.$on('$viewContentLoaded', function () {
       ...some code...
       console.log(myId) // undefined
       console.log(myId.id) // undefined
       ...some code...
    });
});

I could really use some assistance with this situation.

Answer №1

It became clear to me what the issue was, $scope.myDataFirst = data; is being set inside the $http.get() function and since this call is asynchronous, it does not immediately set the value of data.

However, the JavaScript engine does not wait for the asynchronous call to complete, causing $scope.myDataFirst.US; to throw errors which ultimately leads to an undefined value being assigned to

myId = $scope.singleNiche // here
.


Resolution:

  • Place all code inside the success callback as shown below.
  • You have not implemented error handling in your code, which is crucial when dealing with ajax calls.

JS CODE:

$http.get('js/afro.json').then(
   successHandler,
   errorHandler
);

function successHandler(data){
   $scope.myDataFirst = data;
   $scope.singleNiche = $scope.myDataFirst.US;
   $rootScope.header = $scope.singleNiche;
   $rootScope.myDataVar = $scope.myDataFirst.US;

   $scope.setCountry = function (choice) {
      switch (choice){
        case "US" : $scope.singleNiche = $scope.myDataFirst.US;
            break;
        case "UK" : $scope.singleNiche = $scope.myDataFirst.UK;
            break;
        case "SA" : $scope.singleNiche = $scope.myDataFirst.SA;
            break;
        case "CAN" : $scope.singleNiche = $scope.myDataFirst.CAN;
            break;
        case "AU" : $scope.singleNiche = $scope.myDataFirst.AU;
            break;
     }
     $cookies.put("myCountry", choice);
     $rootScope.header = $scope.singleNiche;
  };
    $rootScope.bodylayout = "home-page";
    myId = $scope.singleNiche;
}

function errorHandler(error){
   //display error message if async call fails.
}

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

Turn off bodyparser when uploading files in Node.js

This query is quite similar to another one on Stack Overflow regarding how to disable Express BodyParser for file uploads in Node.js. The solution provided there was for Express3, but when tested with the updated Express 4, it didn't work as expected. ...

Steps for integrating WebRTC recording functionality with a Node.js server

Looking to develop a user-friendly video blogging solution that utilizes WebRTC technology for direct recording of video/audio within the browser, similar to Youtube's My_Webcam. The backend should be powered by Node.js. While exploring various Node. ...

The callback function is unable to access this within the $.post method

Hey there, I'm new to JavaScript/jQuery and I could use some help. I have an object prototype called Page that contains an array and a function for making an AJAX POST request and processing the response. Here's a snippet of the code: function P ...

Getting started with WebTorrent: A beginner's guide

I have been brainstorming some ideas for using WebTorrent. While I am comfortable with JavaScript and jQuery, I have never ventured into Node.js or Browserify territory. Can someone guide me through how to implement the following straightforward code? var ...

What are the key principles of designing web and native mobile applications using React.js architecture?

I am intrigued by the idea of incorporating React.js for server-side rendering into my web service. However, I am facing a challenge when trying to transition from my current web service built with Express.js. At present, my web service caters to two platf ...

Using an imported material icon as a background in JSS styling

I have implemented a draggable dialog component in React-mui with a resizable box feature. const styles = theme => ({ resizable: { position: "relative", "& .react-resizable-handle": { position: "absolute" ...

Items within a shared container are currently displaying stacked on top of each other

I am facing an issue with my bike images and manufacturer names appearing on top of each other instead of next to each other. Despite using "col-md-12", the grid columns are not aligning horizontally as expected. How can I adjust the code so that each imag ...

Guide on automatically navigating pages using HTML

My dilemma involves two HTML pages: flash.html main.html I am seeking a solution where the flash.html page is loaded first for 5 seconds, after which the main.html page should automatically load. How can I achieve this? I attempted to use setTimeout(fu ...

Adding information to Response in Laravel

I am currently working on a function that retrieves information related to two specific IDs. I would like to include these IDs in the response along with the success message. Below is my code: The Controller function calls another function in the Reposito ...

Is @babel the solution to transpile Array.prototype.flat?

I accidentally caused a backward compatibility issue in my React application by utilizing Array.prototype.flat. I was quite surprised that this problem persisted even after transpiling - I had assumed it would generate es2015-compatible code. Is there a w ...

Overcome the issue of 'Parsing Error: Kindly verify your selector. (line XX)' in Javascript/AWQL

Hello there! Just to clarify, I am not a developer and my coding skills are limited to basic HTML. Your patience is greatly appreciated ...

What is the mechanism through which a nested function within an event handler obtains the event object?

How is the e object available to the nested function inside handleClick2 when only the input object is passed? Is this related to the concept of Lexical Environment? handleClick2 = (input) => (e) => { this.setState({ [input]: e.target.va ...

A guide on exporting data from Python in JSON format

I have a python program that can parse data from HTML files, but I need it to save the output as a json file. import glob import json from bs4 import BeautifulSoup for filename in glob.iglob('*.html'): with open(filename) as f: soup ...

Elements that are hidden or not displayed are still able to receive mouse over events

I am in the process of learning how to handle events within svgs and I have encountered a strange issue. Currently, I am working on an infovis project where I create an interface to display various column-graphs. This part is functioning well so far. Ho ...

Can we not customize a nested component using the 'styled()' function in MUI?

Looking at the code snippet below, my attempt to style an MUI Stack component within an MUI Dialog component seems to be falling short. The Stack styles are not being applied as expected: const CustomDialog = styled(Dialog)(({ theme }) => ({ ' ...

Incorrect script enqueue order in child theme of WordPress

Help needed with enqueuing a script in a WordPress child theme. Despite specifying Jquery dependency, the script is loaded before Jquery. The code in question: add_action( 'wp_enqueue_scripts', 'child_theme_scripts' ); function child_ ...

The Parse-JS-SDK currently doesn't support using the objectId in the matchesKeyInQuery method

javascript "parse-server": "^2.6.3", "parse": "^1.10.0", In my database, there are three tables: Member, Circle, and MemberCircle. The Circle table has a pointer field called member, which indicates who created the circle. On the other hand, the Memb ...

My pure JS component is not being recognized by ASP.NET Core when integrated with Vue.js

I decided to try writing a simple component in "ASP.NET Core with Vue.js" template using pure JS instead of Typescript. However, I encountered an issue where my port does not seem to work properly. What could be causing this problem? in ./ClientApp/compon ...

Difficulty displaying data from a Django for loop on the template

I am using an API service and I do not want to save the retrieved data in my database. My goal is to display this data directly on my HTML template. However, I am facing an issue where only the first data from the for loop is showing up in the template, ev ...

Restrict creation of Network Interfaces without attached Network Security Groups using Azure Policy

Hello, I am interested in implementing an Azure Policy that prohibits the creation of Network Interfaces without an NSG attached. After searching through the built-in roles, I couldn't find anything relevant. Does anyone have a script that can help wi ...