How can one capture value of a local variable for use inside Observable.map()
callback? For example, in my Anglar2 application I would love to capture value of quantity
for use in findItem().map()
:
let quantity : number = 1; //<-- needs to be captured
let ordered : string[] = [];
//not interested in actual results, just adding queried items to cart
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
will show quantity 1 for all items (because value of quantity
is always 1 at the end of the loop).
My research shows that this is very common problem in JavaScript, and there are plenty of examples how to capture a variable in for
loops. I wasn't able, however, to find any information how to capture variable values for use in callback s, such as Observable.map()
Use a const within your for
loop.
for (let entity of res.entities) {
if(entity.entity == 'item') {
const q = quantity; //here or somewhere
queries.push(
//..... use q instead
}
else if(entity.entity == 'quantity') quantity = entity.value;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.