Is there a way to retain the local variable value for use within the callback of Observable.map()
? In my Angular2 project, I need to access the value of quantity
inside findItem().map()
:
let quantity : number = 1; //<-- needs to be captured
let ordered : string[] = [];
//just adding queried items to cart, not concerned with results
let queries : Observable<void>[] = [];
//res.entities are NLP classified entities, either item_id:string or quantity:number
for (let entity of res.entities) {
if(entity.entity == 'item') {
queries.push(
this.findItem(entity.value).map(item => {
if(item != null)
{
for(let i : number = quantity; i > 0; i--) this.cart.addItem(item);
}
ordered.push(quantity + 'x ' + item.fullName);//NL message for user
}));
quantity = 1;//reset quantity
}
else if(entity.entity == 'quantity') quantity = entity.value;
}
return Observable.forkJoin(queries, ...);
The ordered
array will display quantity 1 for all items as the value of quantity
is always 1 at the end of the loop. This issue seems to be common in JavaScript, particularly when trying to capture a variable in for
loops. However, information on capturing variable values for use in callbacks like Observable.map()
is scarce.