I have in my controller:
$scope.test= function () {
var list = ["var0","var1","var2","var3"];
var result= 0;
for (var x=0;x<list.length;x++) {
result= result + TestService.loadVariable(list[x])
}
$scope.result = result;
}
and my service is:
loadVariable : function(name) {
return $http({
method: 'GET',
url: "/test/sheet/loadVariable/",
params: {name: name},
}).then(function success(response) {
return response.data;
}, function error(response) {
});
},
The problem is that I always get 0 in the result and I think it's because the loadvariables methods don't have time to execute, any suggestions?
The service
$http
returns a promise so you can use the service$q
to wait for the promises to finish executing using theall([])
. What this method does is wait for all the promises to be executed and then executes the methodthen()
that gives you the responses of each request.For example, here an ajax is executed according to the number of times that it is indicated and see how in the end all the responses are obtained:
In your case it would be:
You could try it as follows:
It is simply to add the values and by means of a counter to know when the cycle reaches the end, immediately when it reaches the end, the final value is assigned to the required variable.