Reputation: 150
so i have a controller where i call a service that gets me items from the data base, I store these items in an Array then i use this array in another function, only when i do so the length of the array changes so my loop starts over everytime i'm still quite confused when it comes to the behavior of the callbacks and i think this is the reason behind this problem, here is my code :
my service :
//get a task by id
getTachebyId : function(id_Data){
return $http.get('/api/taches/' + id_Data);
},
The controller :
//Récupérer les enregistrements de la feuille de temps :
FT.getFT().then(function (result) {
for(var i=0; i<result.data.ftListe.length;i++)
{
//Récupérer le collaborateur :
Compte.getComptesbyId(result.data.ftListe[i].collaborateurid).then(function(result)
{
lecollaborateur.push(result.data.col);
});
// Récupérer les taches remplie dans la feuille de temps et le projet équivalent
Tache.getTachebyId(result.data.ftListe[i].tacheid).then(function(result)
{
task.push(result.data.tachelistes);
});
}
$scope.ftListe = result.data.ftListe;
$scope.task = task;
$scope.lecollaborateur = lecollaborateur;
//$scope.projets = projets;
});
//my function where I use the task array :
$scope.calculTotal= function(id)
{
var couttotal=0;
var count =0;
console.log(task.length);
for (var j=0;j<task.length;j++)
{
if(task[j].projet_id==id)
{ //code }
}
};
result of console.log(task.length) :
How can I get directly length = 5 ?
Upvotes: 0
Views: 76
Reputation: 1261
That appears because of sequential resolve of the promises you've got from $http.get. You could place all your promises in an array, use them with Promise.all()
, and return it only when all the promises are resolved.
You can use $q
in the same way in an Angular app.
Upvotes: 1