Search code examples
javascriptangularjsangular-promiseangular-httpng-controller

AngularJS two http get in one controller make problems


i have two http GET in one controller and sometimes it works and two of them are working. sometime only one http Get is work. and sometimes none of them is 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:

https://prnt.sc/k5ewd6


Solution

  • Chain the two $http.get operations:

    }).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;
           });
    

    Because calling the .then method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.

    For more information, see AngularJS $q Service API Reference - chaining promises