簡體   English   中英

Angular2 Observable.map捕獲局部變量的值

[英]Angular2 Observable.map capture value of local variable

如何在Observable.map()回調中捕獲局部變量的 例如,在我的Anglar2應用程序中,我希望捕獲在findItem().map()使用的quantity .map 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, ...);

ordered將顯示所有項目的數量1(因為quantity值在循環結束時始終為1)。
我的研究表明,這是JavaScript中非常常見的問題,並且有很多例子如何在for循環中捕獲變量。 但是,我無法找到有關如何捕獲變量值的任何信息,以便在回調中使用,例如Observable.map()

for循環中使用const。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM