A guide to efficiently fetch JSON data synchronously using AngularJS

Trying to fetch data from a JSON file using AngularJS results in an error due to the asynchronous nature of the call. The code moves on to the next step before receiving the data, causing issues. The $http.get method was used.

$http.get('job.json').success(function (response) {
  $scope.big = response;      
});

Any suggestions for a synchronous method to retrieve JSON data?

{
  "days": [{
    "dayname": "Sun,23 Aug 2015",
    "date": "2015-08-23",
    "hours": "hoursArray(array24)"
  }, {
    "dayname": "Mon,24 Aug 2015",
    "date": "2015-08-24",
     "hours": "hoursArray(array24)"
  }, {
    "dayname": "Tue,25 Aug 2015",
    "date": "2015-08-25",
    "hours":"hoursArray(array24)"
  }, {
    "dayname": "Wed,26 Aug 2015",
    "date": "2015-08-26",
    "hours": "hoursArray(array24)"
  }]
}

The jQuery file currently being utilized:

(function($) {
$.fn.schedule = function(options) {
var methods = {
init : function(ele, opt) {
//methods.currentdate = methods.now.getFullYear() + "Engine Change" + methods.now.getMonth() + "Engine Change" + methods.now.getDate();
methods.currentdate = methods.now.getFullYear() + "-" + methods.now.getMonth() + "-" + methods.now.getDate();
// $("#scheduleAllDays > *").each(function(){
// var item = $(this);
// $("#scheduleAllDays").width($("#scheduleAllDays").width()+item.width());
// });
// $("#scheduleAllDays").width($("#scheduleAllDays").width());
ele.find("[data-row]").each(function() {
var drow = $(this), drowset = $("[data-row='" + drow.data("row") + "']");

var maxheight = methods.elesMaxHeight(drowset);
drowset.height(maxheight);
});
methods.allocateDurations(ele);
$("#scheduleContentInner", ele).css("min-height", $(".schedule-drag-wrap", ele).innerHeight());
},
elesMaxHeight : function(ele) {
var heights = $(ele).map(function() {
return $(this).height();
}).get();
return Math.max.apply(null, heights);
},
allocateDurations : function(ele) {
methods.flightdata = {
routes : {}
};
ele.find("[data-flight-row]").each(function(i, ival) {
var flight = $(this);
methods.flightdata.routes["row" + i] = [];
flight.find("[data-flight-record]").each(function() {
var currentFlight = $(this), flightrecord = methods.makeStringToObject(currentFlight.data("flight-record"));
flightrecord.element = currentFlight;
methods.flightdata.routes["row" + i].push(flightrecord);
});
});
methods.positionSet(ele);
},
positionSet : function(ele) {
var dayelement = $("#scheduleAllDays > *", ele);

var totaldaywidth = $("#scheduleAllDays").width() + 30;

var totaldays = dayelement.size();

var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var divider = $(".schedule-h-divider");
dayelement.each(function(i, ival) {
var dayele = $(this), dividerele = divider.eq(i);
dividerele.css({
top : $("#scheduleAllDays").height(),
left : dayele.offset().left - 104
});
});
for (var i in methods.flightdata.routes) {
var iobj = methods.flightdata.routes[i];
for (var j in iobj) {
var jobj = iobj[j];
var duration = jobj.duration, width = Number(methods.hmtosec(duration, ".") * perSecondsWidth);
var parent = jobj.element.parent();
jobj.element.css({
// position : "relative",
width : width + "px",
overflow : "hidden",
"white-space" : "nowrap"
}).parent().css({
// width : width+"px",
// overflow : "hidden"
// position:"absolute",
left : (j==0)?0:parent.prev().position().left+parent.prev().width()
});
}
}
methods.dragInit(ele);
},
setCurrentTimeMarker : function(ele) {
var marker = $(".schedule-current-time-marker");
var markerpills = $(".schedule-time-marker-pills");
var dayelement = $("#scheduleAllDays > *", ele);
var totaldaywidth = $("#scheduleAllDays").width() + 30;
var totaldays = dayelement.size();
var totalSeconds = (((totaldays * 24) * 60) * 60);
var perSecondsWidth = Number(totaldaywidth / totalSeconds);
var currentdate = new Date();
var format = currentdate.getFullYear() + "Engine Change" + currentdate.getMonth() + "Engine Change" + currentdate.getDate();
var currentdateele = $("#scheduleAllDays").find("[data-date='" + format + "']");
var days = (currentdateele.index()), seconds = ((days * 24) * 60) * 60;
seconds = seconds + methods.hmtosec(currentdate.getHours() + "." + currentdate.getMinutes(), ".");
marker.stop().animate({
top : $("#scheduleAllDays",ele).height()-53,
left : (seconds * perSecondsWidth) - (marker.width() / 2)
}, 1000, "swing");
markerpills.html(currentdate.getHours() + ":" + currentdate.getMinutes());
methods.markermove = setInterval(function() {
currentdate = new Date();
marker.css({
left : marker.position().left + perSecondsWidth
}, "fast", "swing");
markerpills.html(methods.makezerodigit(currentdate.getHours()) + " : " + methods.makezerodigit(currentdate.getMinutes()));
// methods.schedulemove(ele,perSecondsWidth);
}, 1000);
},
schedulemove : function(ele,seconds) {
var dragwrap = ele.find(".schedule-drag-wrap");
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragwrap.width() - ($(window).width() - routewidth));
if (Math.abs(dragwrap.position().left) < Math.abs(maxleft)) {
dragwrap.css({
left : (dragwrap.position().left - (dragwrap.width)) + "px"
});
}
},
makezerodigit : function(digit) {
return (String(digit).match(/^[0-9]$/)) ? "0" + digit : digit;
},
dragInit : function(ele) {
var currentdaycol = $("[data-date='" + methods.currentdate + "']");
ele.find(".schedule-drag-wrap").css({
left : -(currentdaycol.position().left - 50) + "px"
}).animate({
left : -currentdaycol.position().left - 0 + "px"
}, 1000, "swing", function() {
methods.drag(ele);
methods.setCurrentTimeMarker(ele);
});
},
drag : function(ele) {
methods.move = null;
$(".schedule-drag-wrap", ele).on("mousedown", function(e) {
var dragele = $(this), position = dragele.position();
methods.move = {
x : e.pageX,
y : e.pageY,
left : position.left
};
}).on("mouseup mouseleave", function(e) {
var dragele = $(this);
if (methods.move) {
methods.move = null;
dragele.removeClass("userselect-none cursor-move");
}
}).on("mousemove", function(e) {
var dragele = $(this), position = dragele.position(), movedx, drag = true;
if (methods.move) {
methods.curmove = {
x : e.pageX,
y : e.pageY
};
var routewidth = $(".schedule-route:eq(0)").width() + $(".schedule-route:eq(1)").width();
var maxleft = -(dragele.width() - ($(window).width() - routewidth));
var xcondition = (methods.move.x > methods.curmove.x);
dragele.addClass("userselect-none cursor-move");
if (position.left <= maxleft && xcondition) {
drag = false;
dragele.css({
left : maxleft
});
}
if (position.left > -10 && !xcondition) {
drag = false;
dragele.css({
left : 0
});
}
if (drag) {
//if direction right to left
movedx = methods.move.left + (methods.curmove.x - methods.move.x);
dragele.css({
left : movedx
});
}
}
});
},
now : new Date(),
currentdate : "",
hmtosec : function(hours, identy) {
var s = (hours.match(/\./)) ? hours.split(identy) : [hours, 0], h = s[0], m = s[1];
h = (Number(h)) ? (h * 60) * 60 : 0;
m = (m == 0) ? 0 : m * 60;

return Number(h + m);

},
makeStringToObject : function(string) {
var loc_string = String(string).split("|");
var output = {};
for (var i in loc_string) {
var keyvalue = loc_string[i].split("~");
output[keyvalue[0]] = keyvalue[1];
}
return output;
}
};
return this.each(function() {
methods.init($(this), $.extend({}, $.fn.schedule.setting, options));
});
};
$.fn.schedule.setting = {};
})(jQuery);
The encountered error: Uncaught TypeError: Cannot read property 'left' of undefined

Answer №1

When utilizing a service:

var deferred = $q.defer();
       $http.get('job.json')
    .success(function(response) {
     defer.resolve(response);
    }).error(function(error){
    console.log(error);
    })
        return deferred.promise;

In the controller section:

var p=<serviceCall>
p.then(function(s){
$scope.ans=s;
})

The $q serves the purpose of obtaining synchronous responses. For further information please visit:https://docs.angularjs.org/api/ng/service/$q

Answer №2

Performing a synchronous HTTP request is not possible because the response (which in this case is the JSON file) cannot be instantly loaded. However, when using $http.get, it returns a promise that resolves once the request is complete. To handle actions after the JSON file has been loaded, you should execute them within the then block of the promise.

$http.get('data.json').then(function (response) {
  $scope.data = response;
  // Carry out any additional tasks after loading the JSON file.
});

Answer №3

To update your value, use promise.then in the following code snippet:

    var promise=$http.get('data.json');
    promise.then(function(data){
                  $scope.value=data;
    });

An alternative approach is shown below:

   function fetchObj(callback){
    $http.get('data.json').success(callback);
   } 

  fetchObj(function(output){
   console.log(output)
   // include your jQuery script here
  })

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

Unleashing the power of async/await in React: A comprehensive guide

Looking to simplify my code, I am interested in implementing async and await for the following code snippet. However, I am unsure of how to proceed. Any examples would be greatly appreciated. deletePost = (post) => { var post_id = post; try { ...

Issue with Date generation in TypeScript class causing incorrect date output

I have a simple code snippet where I am creating a new Date object: var currentDate = new Date(); After running this code, the output value is: Sat May 11 2019 13:52:10 GMT-0400 (Eastern Daylight Time) {} ...

How can one determine when an animation in Three.js has reached its conclusion?

When I write code like this: function renderuj(){ scene.renderer.setClearColor(0xeeeeee, 1); ob1.animation.update(0.5); ob2.animation.update(0.5); scene.renderer.render(scene.scene, scene.camera); animationFram = reques ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

What is the process for integrating a gltf model into Aframe & AR.js with an alpha channel?

--Latest Update-- I've included this code and it appears to have made a difference. The glass is now clear, but still quite dark. Note: I'm new to WebAR (and coding in general).... but I've spent days researching online to solve this issue. ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

Control Center for JavaScript Administration

When dealing with Javascript content on a larger website, what is the best way to efficiently manage it? I am facing challenges with multiple $(document).ready()'s and the need to handle numerous id strings ($('#id')). One idea was to combin ...

Is there a way to compel @keyframes to continue playing until it reaches its conclusion even after a mouseout event

Whenever I hover over an element, a keyframe animation starts playing. However, when I move the cursor away, the animation stops abruptly. Is there a way to ensure that it plays until the end? I've tried using the animationend event, but it doesn&apos ...

Variable Assignment in Twig: A Dynamic Approach

I am facing a challenge with dynamically assigning variables in Twig within a loop. I have JSON data that is passed into the template and I want to create variables for each object without being able to modify the JSON format. [{ "name": "firstName", ...

Is the AngularJS version significant in determining outcomes?

Just delved into the world of AngularJS and encountered a puzzling issue. Here's what I've been struggling with: I crafted a piece of code in app.js var myApp = angular.module("myApp",[]); myApp.config(['$routeProvider', function($ro ...

establish connections within dynamic data table entries

As a newcomer to Javascript, I've been struggling with a particular question for some time now. The challenge at hand involves a dynamic jQuery table where I aim to hyperlink one row of the table data to a .php page in order to perform certain querie ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Merge three asynchronous tasks into a single observable stream

I have 3 different observables that I am using to filter the HTML content. Here is the TypeScript code snippet: fiscalYear$ = this.store$.select(this.tableStoreService.getFiscalYear); isLoading$ = this.store$.select(this.tableStoreService.tableSelector ...

Running NPM module via Cordova

After developing an app using cordova, I encountered a challenge where I needed to incorporate a node module that lacked a client-side equivalent due to file write stream requirements. My solution involved utilizing Cordova hooks by implementing an app_run ...

Having trouble with jQuery Ajax not transmitting data properly in a CodeIgniter project?

I am brand new to the Codeigniter MVC framework. Whenever I attempt to send data through ajax from the views to the controller, I encounter an error. Please click here to view the image for more details. Here is the code snippet: views/ajax_post_view.php ...

How to Handle Empty Input Data in JQuery Serialization

Having an issue with a form that triggers a modal window containing another form when a button is clicked. The second form includes an input field and send/cancel buttons. The goal is to serialize the data from the modal form and send it to a server using ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

What is the name of the JavaScript code editor that includes line numbering for plain text?

Looking to incorporate a text area with line numbering features. I experimented with EditArea, but encountered difficulties when working with text files. While syntax highlighting for various programming languages would be a nice touch, my primary focus ...

Node.js app experiencing intermittent issues with AngularJS interceptor failing to include JWT Bearer token in all requests

I have implemented a JWT authentication system in a node app. To ensure the Bearer token is included in every request, I used an interceptor. It functions correctly when accessing a restricted route within Angular or by using curl with the token specified ...

Utilizing JQUERY and AJAX for conditional statements

I am currently in the process of creating a basic chat bot. At this point, the bot replies when the user inputs a pre-defined question. However, I am trying to figure out how to program the chatbot to respond with a "sorry, I don't understand" message ...