The code below cycles through a list of tags (strings) and gets info and then images from services. Then it pushes a newly created and assembled ProductItem
object to an array of products that now are populated with images.
var toReturn = [];
for (var i in tags){
var productItem: ProductItem= new ProductItem();
self.productService.getInfo(tags[i])
.subscribe(function(info){
productItem.info = info;
self.productService.getImages(tags[i])
.subscribe(function(imageUrls){
productItem.images = imageUrls;
toReturn.push(productItem);
});
});
}
However, there is a problem here.
The problem is that I end up with a toReturn
array filled with identical products - all of them corresponding to the last tag in the tags
array.
I realized that this must have to do with the scoping for ProductItem
. I think that since the last element in tags is creating the last productItem
, all of the unfulfilled promises/observables are fulfilling on this final productItem
and not their own productItem
which I expected them to retain.
Does anyone have any ideas on how to get around this problem?