Issues arise when attempting to use two HTTP get requests in a single AngularJS controller

Having two http GET requests in one controller, causing intermittent issues where only one of the GET requests works or sometimes none of them are shown. Any suggestions?

 }).controller("nextSidorAdminCtrl", 
 function($scope,$rootScope,$http,$location,$state) {
   $http.get("/ShiftWeb/rest/admin/getallsettingtime")
  .then(function(response) {
    $scope.settingtimes = response.data;
 });    
 $http.get("/ShiftWeb/rest/admin/nextsidor")
    .then(function(response) {
    $scope.nextsidor = response.data;
 });

Image:

Answer №1

Connect the two $http.get requests:

}).controller("nextSidorAdminCtrl", 
   function($scope,$rootScope,$http,$location,$state) {
       $http.get("/ShiftWeb/rest/admin/getallsettingtime")
       .then(function(response) {
           $scope.settingtimes = response.data;
           return $http.get("/ShiftWeb/rest/admin/nextsidor")
       })    
       .then(function(response) {
           $scope.nextsidor = response.data;
       });

By utilizing the .then method of a promise to return a new derived promise, it becomes simple to construct a sequence of promises. This allows for creating chains of varying lengths and deferring resolution of promises as needed, by resolving a promise with another promise in the chain.

To learn more, visit the AngularJS $q Service API Reference - chaining promises

Answer №2

To effectively tackle this issue, the recommended approach is to utilize the "async" library.

In my view, the flaw in Mr. georgeawg's solution lies in the fact that if

$http.get("/ShiftWeb/rest/admin/getallsettingtime")
returns a success response, then
$http.get("/ShiftWeb/rest/admin/nextsidor")
will be invoked; otherwise, it won't be executed.

Looking at the question, it appears that both operations are independent of each other.

Hence, it is advisable to adopt a method like async for handling such scenarios.

The revised code snippet would look like this:

 var getAllAettingTime = function(cb) {
      $http.get("/ShiftWeb/rest/admin/getallsettingtime")
      .then(function(response) {
          if(response.data){
                   $scope.settingtimes = response.data;
                    return cb(null,'OK');
          }else{
                    return cb(null,'ERROR');
       })
}

 var nextSidor= function(cb) {
   $http.get("/ShiftWeb/rest/admin/nextsidor")
   .then(function(response) {
          if(response.data){
                   $scope.nextsidor = response.data;
                    return cb(null,'OK');
          }else{
                    return cb(null,'ERROR');
       })
}

async.series([ getAllAettingTime, nextSidor], function(err, result) {
  if (err){
             /* Handle error conditions here */
  } else {
              /* Proceed if both HTTP requests succeed */
   }
});

In the above async.series() call, both HTTP requests are initiated independently of one another.

For further insight, it is recommended to delve into the details of the async npm module and incorporate it into your application.

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

AngularJS directive called 'dataSharing' operates

Something strange is happening here. Not functioning properly scope: { 'dataSource': '='} Functioning well scope: { 'mySource': '='} Working perfectly scope: { 'data': '='} Could someone ex ...

Mastering the art of completing a form using AJAX

I'm working on a checkbox that triggers AJAX to create a new log. It populates the necessary information and automatically clicks the "create" button. However, I'm facing an issue where the hour value is not changing. Any help on what I might be ...

Retrieve the specific data from the database when the <tr> element is hovered over

Hey everyone, I've been struggling with a problem for some time now. I have a loop that retrieves values from a database and I want each value to display onmouseover using JavaScript. However, it's only showing the value of the first row for all ...

Show or hide the legend on a highchart dynamically

I am currently utilizing highchart in my application and I am interested in learning how to toggle the visibility of the legend within the highchart. Here is what I have attempted: var options = { chart: { type: 'column&a ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...

Utilizing SVG within Sproutcore allows for seamless access to DOM nodes and the ability to effortlessly bind Sproutcore events directly to the DOM

Exploring Sproutcore, I am delving into the world of SVG (Standard Vector Graphics) integration within the app. The goal is to utilize a canvas for drawing elements like lines, boxes, and images, all of which SVG offers. My approach involved incorporating ...

Error encountered by React context: TypeError - Attempting to iterate over an object that is not iterable (unable to access property

I'm encountering this error: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) whenever I attempt to handle state using useContext. The purpose here is to initialize "tokens" as an empty array [] on page load, and then ...

What is the best way to position a container div over another container using Bootstrap or CSS?

https://i.sstatic.net/q1qGi.png I'm working on a Bootstrap 4 layout where container B needs to overlay part of container A. I want to achieve a design where container B appears on top of container A. Any suggestions or references on how to achieve th ...

Store JWT as a cookie in Vue JavaScript and ensure it is successfully saved before proceeding

Upon logging in, my page sends the login and password information to the backend, receives a jwt token in return, saves it to the cookies, and redirects to /home. However, there seems to be an issue with the authentication check on the /home route. When c ...

JavaScript does not recognize the $ symbol

Firebug is indicating that there is an issue with the $ variable not being defined. I have a basic index.php page that uses a php include to bring in the necessary content. The specific content causing the error is shown below: <script type="text/jav ...

Deconstructing arrays in the req.body object in a Node.js Express application

Received an array in the request body as follows: [ { "month" : "JUL", "year" :"2018" }, { "month" : "JAN", "year" :"2018" }, { "month" : "MAR", "year" :"2018" } ] This array consists of two parameters (month:enum and year:string). ...

Exploring the global document object within Next.js

We have been working on a project using nextjs and are facing an issue with changing the styling of a button upon click. Despite using document.getElementById, we are unable to change the styling no matter what we try. pages/index.js function Index() { ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

Instructions on removing rows by using buttons within a JavaScript-generated table

This snippet displays JS code to create a quiz index table and HTML code to display the index. function load(){ var data = [ { "id": "qc1111", "quizName": "Quiz1", "course": "111", "dueDate": "1/ ...

Ways to address the warning "promise rejections are deprecated"

I am struggling to understand promises and keep encountering an error about unhandled promise rejection, even though I have a catch block for handling rejections. Can anyone help me figure out what I am doing wrong? Below is the code I am working with: v ...

"Implementing React to dynamically load and update value in component, enabling user interaction with the

As a newcomer to the world of React (16.4.2), I am trying to grasp its functionality without delving into Redux just yet; my focus is solely on understanding the core React library. In my application, there is an input component called RangeInput, which r ...

When attempting to display the details of each restaurant on my detail page, I encountered the error "Cannot read property 'name_restaurant' of undefined."

I have set up dynamic routing for a ProductDetail page, where each restaurant has its own details that should be displayed. The routing is functional, but I am facing difficulty in retrieving data from Firestore using the restaurant's ID. PS: Althoug ...

Connecting a text input in a nested component to the data passed down from its parent component in VueJS

My VueJS setup involves a child component sending data to a parent component, which then tries to route the data to a sibling of the child to create new components. I'm using a dictionary to group the data and push it into an array. The array is then ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...

The execution of the code may encounter errors initially, but it generally runs without any issues on subsequent attempts

I recently developed a piece of code to ascertain whether a value in the database is null or not. Here's the snippet: var table; var active = false; function CheckActive(table){ this.table = "table" + table + ""; var db = window.openDatabas ...