What is the best method for extracting data from the most recent HTTP request?

One issue I am facing is that the http request is fetching data from the last request loaded instead of the most recent one. Is there a way to cancel the previous call and retrieve the new one?

The Component:

this.searchForm$.valueChanges
    .pipe(debounceTime(500))
    .subscribe((selectedValue) => {
        this.loading = true;
        this.sExperienceSearch = {...selectedValue.sExperience,...selectedValue.sExperience2,...selectedValue.sExperience3,...selectedValue.sExperience4}
        this.sExperienceSearch.importanceMap = {...selectedValue.sExperience.importanceMap,...selectedValue.sExperience2.importanceMap}
        this.apiService
            .getSearch(this.sExperienceSearch)
            .subscribe((data: any) => {
                this.firstCall = false;
                this.loading = false;
                this.selectedValue = this.sExperienceSearch;
                this.searchData = data;
                this.numVendors = this.searchData.numVendors
                    ? this.searchData.numVendors
                    : 0;
            });
    });

The Service:

 return this.httpClient
        .post<any[]>('/api/advanced-search', body, httpOptions)
        .pipe(
            distinctUntilChanged(),
            map((data) => {
                return data;
            }),
            catchError((error) => {
                return throwError('Something went wrong!');
            })
        );

Answer №1

Within your component, you currently have multiple subscriptions occurring after each search event, leading to the longest lasting HTTP call providing the answer.

To remedy this situation, it is crucial to cancel the subscription to an HTTP call as soon as a new search request is initiated. This approach ensures that you only receive the result for the most recent search query, rather than the one that completes last.

You are already utilizing RxJS pipe operators in your code; consider implementing the switchMap operator to accomplish this objective. Here is a helpful pointer to guide you in the right direction:

Component Logic:

this.searchForm$.valueChanges
    .pipe(
      debounceTime(500),
      distinctUntilChanged(),
      switchMap((selectedValue) => {
        this.sExperienceSearch = {...selectedValue.sExperience, ...selectedValue.sExperience2, ...selectedValue.sExperience3, ...selectedValue.sExperience4};
        this.sExperienceSearch.importanceMap = {...selectedValue.sExperience.importanceMap, ...selectedValue.sExperience2.importanceMap};
        return this.apiService.getSearch(this.sExperienceSearch);
      })
    ).subscribe(...subscribelogic...);

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

passing data through URL in Angular 7

Looking to pass a parameter in the URL while using Angular 7, to achieve a format like example.com/search/users?q=tom. Below is the syntax I am currently using in my service: public searchUsers(obj):any{ return this._http.get('example.com/s ...

Can we streamline a generic overloaded function's signature to make it more concise?

I have developed a streamlined Axios wrapper function that integrates zod-parsing and presents a discriminated union for improved error handling. While the implementation successfully maintains the default behavior of Axios to throw errors in certain cas ...

What is the process for retrieving information from the subscribe module in Angular 7?

As a newcomer to Angular 7, I am facing an issue with returning data from a component function. Due to my limited understanding of Angular 7, I may not be phrasing the question correctly. Below is the code snippet of my component function: getUserStatus ...

Applying ngStyle based on changing information

I am struggling with setting the fill and stroke of an SVG path element based on the values in an array named shirts. <path class="st2" style="stroke-width:2.0;" [ngStyle]="myStyle(4)" d="M11.5,315....315.9z"/> In my code, I have defined a function ...

Encountering an error in Angular when trying to add a dynamic component

I have a straightforward test code for implementing dynamic components in Angular 4. @Component({ selector: 'component', template: ` <ul><li #item *ngFor="let number of list">{{number}}</li></ul> <ng-temp ...

Converting a TypeScript class to a plain JavaScript object using class-transformer

I have a few instances of TypeScript classes in my Angular app that I need to save to Firebase. However, Firebase does not support custom classes, so I stumbled upon this library: https://github.com/typestack/class-transformer which seems to be a good fit ...

Loading lazy modules into tabs in Angular 8 - A comprehensive guide

I'm attempting to implement tabs with lazy loading of feature modules. Here is the code I have so far: Main router: export const AppRoutes: Routes = [{ path: '', redirectTo: 'home', pathMatch: 'full', }, ...

Passing an object to createMuiTheme in Typescript and Material UI

Struggling with TypeScript and Material UI integration, I'm puzzled by the issue of passing an object to createMuiTheme. This code snippet works perfectly: const themeConfig = createMuiTheme({ palette: { primary: green, secondary: purple, ...

Implementing the withAuthenitcationProps method in all page.tsx files to integrate Amazon Cognito authentication

I have been working on my Next.js app and wanted to share the project structure with you: ├── README.md ├── amplify │ ├── #current-cloud-backend │ ├── README.md │ ├── auth │ ├── backend │ ├── cl ...

Error encountered in typescript when trying to implement the Material UI theme.palette.type

Just starting out with Material UI and TypeScript, any tips for a newcomer like me? P.S. I'm sorry if my question formatting isn't quite right, this is my first time on Stack Overflow. https://i.stack.imgur.com/CIOEl.jpg https://i.stack.imgur.co ...

Looking for a way to include an input box within a react-select option dropdown menu

Currently, I am facing a situation where I need to include an input box within my dropdown option menu. The challenge is that I cannot utilize the custom tag creator feature of react select to create a new option with the dropdown. Upon going through the ...

Guide on assigning json array values to multiple accordion forms in Angular 6

Utilizing multiple accordion forms on the same page poses a challenge. When the Add button is clicked, an additional accordion form is added to the page. Upon submitting the second form, a set of JSON data is submitted. The resulting JSON array after three ...

Strange behavior exhibited by the HTML DataList component within an Angular application

I have created a simple component that displays a list of data and allows users to add new entries. <h6 *ngIf="withHeader"><label for="select"> {{title}} </label></h6> <label *ngIf="!withHeader" [ngClass]="{'required&apos ...

Bypass URL Routing for a specific route in Angular 8 and Apache

I currently have two Angular applications: the FrontEnd and Admin. Both of these are hosted on cPanel behind an Apache server. The website setup is as follows: mydomain.com/ ----> Frontend Angular Application mydomain.com/admin ----> Admin Angular ...

Streamlining Your Workflow: Using Angular to Edit Multiple Objects Simultaneously

I utilize a table to display data retrieved from my API. In my .ts component, I use the following method to access the service data: getBloques() { this.configuracioncvService.getBloques() .subscribe(res => { let bloque ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

Expand the width of Angular 9 component to take up the full screen

I am struggling to make the content in my angular template file occupy the entire width and height of the page. Currently, it looks like this: https://i.sstatic.net/LVOz7.jpg However, I want it to look more like this: https://i.sstatic.net/Mnxxx.jpg I hav ...

Troubleshooting Cross Origin Error in C# and Angular

We are currently in the process of developing a website using Angular 5. The backend has been created utilizing .Net Web API and SQL Server. Our plan is to deploy the website on Azure, making it accessible both from the internet and the intranet. After co ...

Issue: Failed to access the 'setDir' property of an undefined object

Greetings, I am a newcomer to Ionic/Angular and have been facing a particular issue for over 20 days now. I have created a small app and would like to implement multi-language support with both RTL and LTR directions. I followed the documentation provided ...

What could be causing the lack of reflection in the UI for the signal update?

Recently, I have been working on some code in SolidJS. Specifically, I am utilizing createSignal to handle the rendering of certain views based on changes within the options array. import { render } from "solid-js/web"; import { createSignal, Sh ...