Reputation: 799
I am trying to make a http request and place the returned result into my array.
I have something like
Ctrl
for (var i=0; i < numOfProduct.length; i++) {
productFactory.makeRequest(numOfProduct[i].id)
.then(function(data) {
console.log(i)
//always output 10 which is my numOfProduct.length
numOfProduct[i].push({detail: data});
//i got Cannot read property 'push' of undefined error
})
$scope.numOfProduct = numOfProduct;
}
productFactory
service.makeRequest = function(id) {
return $http.get('/api/product/get' + id);
}
return service;
My goal is to push a http request result into each of numOfProduct element as an object. However, I can't seem to do that with the http request codes I have. Can anyone help me about it? Thanks so much!
Upvotes: 0
Views: 111
Reputation: 1756
You have two issues with the above:
1 is a common callback issue where you're binding a reference to i
but not to the value of i
. So, by the time your callback gets called, the loop will have finished and i
will be 10 in all of the callbacks that you bound.
One way to fix this is to force evaluation of i
through a function call:
function makeCallback(productId) {
productFactory.makeRequest(productId)
.then(function(data) {
console.log(i)
return ({detail: data});
});
}
The second issue is that you are calling .push
on a specific value in the array numOfProduct
instead of an actual array. (Unless that specific value is an array, which i'm assuming it isn't since you are calling .id
on the value)
Try this instead:
function makeCallback(productId) {
productFactory.makeRequest(productId)
.then(function(data) {
console.log(i)
return ({detail: data});
})
}
var array = [];
for (var i=0; i < numOfProduct.length; i++) {
array.push(makeCallback(numOfProduct[i].id));
}
$scope.numOfProduct = array;
If each loop is being ran asynchronously then I suggest using the popular async libary. Let me know if you need any help setting this up.
Upvotes: 4