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:
The best way to solve this problem is to use async
In my openion, The problem in Mr. georgeawg’s answer is, if $http.get("/ShiftWeb/rest/admin/getallsettingtime")
will return success
then $http.get("/ShiftWeb/rest/admin/nextsidor")
will be called, Otherwise It will not be called.
And as I can see in the question both are independent.
So you need to follow the best way which is used async or something like that.
So your code will be :
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){
/* Do what you want if err comes */
} else {
/* Do what you want if both HTTP come with success */
}
});
In the above async.series()
both HTTP will be called without any dependency on each other.
For better understanding, you need study about async npm module and have to install in your app.
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