Using Angular 2 Observable.map to extract the value of a local variable

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.

Answer №1

Optimize your for loop by using a const variable.

for (const item of res.entities) {
    if(item.entity === 'product') {
        const q = quantity; // define q here or elsewhere
        queries.push(
            //..... replace quantity with q
    }
    else if(item.entity === 'quantity') quantity = item.value;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I make sure to consider the scrollbar when using viewport width units?

I've been working on developing a carousel similar to Netflix, but I'm facing an issue with responsiveness. I've been using a codepen example as a reference: Check out the example here The problem lies in the hardcoded width and height use ...

The ng-change event is triggered for radio buttons that are generated using ng-repeat the first time they appear, but not for subsequent appearances

Is it possible to trigger the updateRow method on every change of a radio button selection? Currently, the updateRow method is only being called the first time the radio button changes. How can I make sure it executes each time there is a change? Html: ...

Opening PDF files will now be done automatically in a new window

A request from one of my clients is to have the links to pdf files on their website open automatically in a new window. I came up with this code that achieves the desired functionality: $("a[target!='_blank'][href$='.pdf']").attr("tar ...

Buttons for camera actions are superimposed on top of the preview of the capacitor camera

I am currently using the Capacitor CameraPreview Library to access the camera functions of the device. However, I have encountered a strange issue where the camera buttons overlap with the preview when exporting to an android device. This issue seems to on ...

Trouble with loading document on 'load' event listener

Primary Concern Currently, my script operates smoothly when it listens for a click event on the element with the id share. I am looking to switch this functionality to activate on the $(document).on(load) event while removing the share button. However, up ...

The user could not be deserialized from the session

I am having an issue with deleting users from my database. When a user is logged in and I try to refresh the page after deleting the user, I encounter the following error message: Error: Failed to deserialize user out of session Below is the code snippet ...

Tips for verifying login credentials with MongoDB and Express: Leveraging db.collection().findOne() or .find() functions

I am encountering an issue with a POST request involving user credentials being sent from a Login page to the API Server. The code looks like this: loginUser(creds) { //creds is in the form of { username: bob, password: 123 } var request = { ...

Is there any more Angular code to be bound using ng-bind-html or ng-bind?

Hey there! Just a quick Angular inquiry: <div class="_minimal_size margin_10_middle"> <div class="_50 espaciado_0_20"> <p ng-bind-html="eirana_knows.feedback"></p> </div> <br class="clear"/> </div ...

JavaScript: incorporating PHP into JavaScript

What is the proper way to incorporate PHP inside Javascript? var timeDiff = 60-20; if ( timeDiff <= 60 ) { var stamp = timeDiff <?php echo $this->__('second ago') . '.'; ?>; } A console error has been detected: Unca ...

Decoding entities in a jQuery AJAX form

I am working on a jQuery AJAX form to add, edit, and delete usernames in a MySQL database. When I retrieve data with special characters from the database, I want to populate the modal edit form with entity-decoded characters. This means that characters lik ...

"Utilizing TypeScript Definitions in a Node.js/Express Application: A Step-by-Step

I initially started using tsd and typings to install declaration files from external sources and reference them in the server file. However, now we have the option to obtain declaration files through @types/filename. I'm not sure why the move was made ...

Organizing outcomes from a for each function into an array using javascript

I have a form with multiple values of the same name, and I need to arrange this data in an array before sending it via AJAX. However, when I try to do this using the .push function, I encounter an error that says "Uncaught TypeError: dArray.push is not a f ...

Transforming Ember's ajax query string

Using ember-model, I am making a request like this: App.Video.find({'sort':'createdAt+asc'}); to retrieve a sorted list of videos. This should result in the following request: http://localhost:1337/api/v1/videos?sort=createdAt+asc How ...

Enable express to disregard specific URL modifications

I'm currently working on creating a Single Page App using Express. One of the challenges I am facing is that the Express route feature forces the view to be re-rendered every time the URL changes and a GET request is sent to the server. My code typica ...

React component encounters rendering issue with if-else statement

I'm attempting to use an if-else statement to check if the photo property contains an item, but for some reason, the code below is not working as expected. I can't seem to figure out what's wrong with it. Everything appears to be correct in ...

Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is restricted to binding with Iterables like Arrays. Unfortunately, there is no current solution available for this issue

I'm encountering a minor issue with my code. I have two HTTP requests and after combining the data from both, I encounter an error when trying to loop through the final array. I've read other posts suggesting that the returned object is not an a ...

What is the best way to pass variables between nested directives?

When a directive called el2 is nested within another directive called el1, I face challenges in accessing variables that are "locally declared" in el1 (such as variables generated by ng-repeat, ng-init, etc) from el2. For a practical example showcasing th ...

Guide to leveraging various build targets while executing the capacitor sync command within an Angular project

In my current Angular project, I have been utilizing Capacitor. Within my angular.json file, I have set up various build targets such as development, staging, and production. To deploy with different configurations, I use the command ng build --configurati ...

Intercommunication of variables among components

My scenario involves two components, namely App and SomeComponent. I'm aiming to access a variable in App from SomeComponent. App: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css& ...

Have Vue props been set to null?

Currently, I have a component within my vue.js application that looks like this: export default { props: ['forums'], methods: { increment(forum, index) { ForumService.increment(forum) .then(() => { ...