Double Calling of Angular Subscription

I am currently working with a series of observables that operate in the following sequence: getStyles() --> getPrices()

Whenever a config.id is present in the configs array, getStyles() retrieves a style Object for it. This style Object is then passed to getLease where a price is added to it and stored in an array named "style"

  getStyles(configs: any) {
      configs.forEach(config => {
           this._APIService.getStyleByID(config.id).subscribe(
                res => {
                    res.config = config;
                    this.getLease(res);
                }
           );
    });

  }

  getLease(style: any): void {
      this._priceService.getPrice().subscribe(
        price => {
            style.price = price;
            this.garage.push(style);
            console.log(this.garage);
        });
  }


}

The challenge I am facing involves duplicate calls being made because the style array contains twice as many objects as necessary. The problem arises from Angular making two calls to this._APIService.getStyleByID() when I expect it to only make one call. How can I adjust my Observables to ensure they are executed only once?

Answer №1

If you want to ensure that the last request gets canceled if there are any changes, consider using switchMap instead of mergeMap:

  retrieveStylesByYear(): void {
    this._APIService.getStylesWithoutYear()
      .switchMap(styles => {
         styles.years.forEach(year => {
          year.styles.forEach(style => {
              this._APIService.getStyleByID(style.id)
           })
         })
      })
      .subscribe(style => {
        console.log('style', style)
      })
  }

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

Combining pixijs with TypeScript in Ionic 2 using npm

To begin, I ran the command npm install -g ionic Followed by ionic start pixiApp blank --v2 Navigated to the pixiApp directory with cd pixiApp Installed necessary dependencies using npm install Added a specific version of pixi.js (4.1.0) with npm install p ...

What is the method for toggling a checkbox on and off repeatedly?

I've been struggling with this piece of code. I've attempted using setTimeout, promises, and callback functions, but nothing seems to work as expected. document.querySelectorAll("input").forEach((el, i) => { setTimeout(() => { ...

Guide on transferring control from a successful jQuery event to an HTML form

I am currently using the following jQuery code to validate user details. $.ajax({ type: "POST", url: "Login", data:'uname='+encodeURIComponent(uname)+'&'+'pass='+encodeURIComponent(pass), ...

Is it possible for TypeScript to convert a generic enum type into a string at runtime?

Enumerations and interfaces are an important part of my codebase: enum EventId { FOO = 'FOO', BAR = 'BAR', } interface EventIdOptionsMap { [EventId.FOO]: { fooOption: string; }, [EventId.BAR]: { barOption: number; } ...

Uncheck the previous option selected in a multi-select dropdown using jQuery

Hey there, I've been facing an issue with my change handler when trying to add or remove values from an Array. It works fine until the last element is selected, at which point the change event does not fire properly. Has anyone else encountered this p ...

Tips for implementing AngularJS on a webpage transfer

I am a beginner in learning AngularJS. I have gone through the basic tips on W3Schools, but now I am stuck on implementing the login function. When I click the "sign in" button, the webpage should redirect to the login page of the website. However, I am ...

Update the second mouse click functionality using jQuery

I currently have a jQuery function integrated into my WordPress portal that manages the functionality of the menu and the display of subcategories to ensure proper mobile optimization. This code, which was created by the theme editor, handles these aspects ...

What are the best methods for cropping SVG images effectively?

Is it possible to crop a large SVG background that has elements rendered on top of it so that it fits the foreground elements? I am using svg.js but have not been able to find a built-in function for this. Can an SVG be cropped in this way? ...

Despite correctly declaring jquery-ui.js and numeric.js, the jQuery datepicker and numeric plugins are not working as expected

element, it's strange that I am not receiving any error messages. However, despite this, the jquery datepicker function and numeric plugin are not working on the intended input fields they are supposed to be linked to. This particular page is a simpl ...

What is the way to obtain loading start/end events while using a loader widget in conjunction with an asynchronous Firebase request (observable)?

I have implemented AngularFire in the following manner: constructor(private afDb: AngularFireDatabase) { allRRs$ = this.afDb.list(`research_reports-published/`).valueChanges(); } The variable allRRs$ is an observable that I am utilizing in my templat ...

Retrieve a particular cookie from the request headers in Express framework

Today, I encountered a problem with express. Let's say we set multiple cookies, but when I check request.headers, only one cookie is returned: cookie: 'userSession=123' For instance, not only is it unreliable to use request.headers.cookie ...

Is it possible to measure the CPU utilization in a TypeScript application programmatically?

Is there a method to calculate CPU usage as a percentage and record it in a file every 20 milliseconds? I'm interested in exploring different approaches for accomplishing this task. Your insights would be greatly appreciated! I've come across so ...

Error: Unspecified process.env property when using dotenv and node.js

I'm encountering an issue with the dotenv package. Here's the structure of my application folder: |_app_folder |_app.js |_password.env |_package.json Even though I have installed dotenv, the process.env variables are always u ...

Javascript program that generates drag and drop elements using HTML5 features:

Whenever I attempt to drag and drop elements that are normally created by HTML, everything works fine. However, when I try to drag and drop elements generated by JavaScript, I encounter the following error: Uncaught TypeError: Cannot read property 'p ...

Why is NestJs having trouble resolving dependencies?

Recently delving into NestJs, I followed the configuration instructions outlined in https://docs.nestjs.com/techniques/database, but I am struggling to identify the issue within my code. Error: Nest cannot resolve dependencies of the AdminRepository ...

Retrieve the present value from a Selectpicker using jQuery within the Codeigniter Framework

I attempted to use DOM manipulation to retrieve the value of the currently selected option from the selectpicker. My goal was to have the value of the selectpicker id="service_provider_select" printed first. However, whenever I changed the option using the ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

Change a Typescript class into a string representation, utilizing getter and setter methods in place of private variables

Below is a snippet of TypeScript code: class Example { private _id: number; private _name: string; constructor(id: number, name: string) { this._id = id; this._name = name; } public get id(): number { return t ...

What is the best way to convert an object into an array of objects for use in a select search functionality

I am attempting to map key and value pairs into a single array in order to use them as selectsearch options. I have successfully mapped each item individually, but now I need to combine all the data into one array. How can I achieve this? Here is how I am ...