Rejecting the request by clicking a button

While switching to a menu, I retrieve data from the API. As the pending data is still loading in DevTools, I click on the Filter button to search for additional data. The data I am searching for appears in my table. However, once the pending data finishes loading, the previously searched data disappears.

This is the command line used to retrieve the data


  protected loadData = (params) => {
    $.ajax({
        method: 'GET',
        url: this.tableUrl,
        data: params.data,
        beforeSend: (request) => {
            request.setRequestHeader('Authorization', `Bearer ${this.authService.getToken()}`);
        }
    }).done((response) => {
        params.success(response);
    });
}

https://i.sstatic.net/fEeGu.png

In the requests provided above, the top request takes approximately 40 seconds to complete while the bottom one takes only 1 second. The faster request retrieves data within 1 second. Therefore, during filtering, data fetched within 1 second gets overwritten by data retrieved after waiting for 39 seconds. To solve this issue, it is necessary to cancel requests related to "referenceTumList?PageIndex=0&PageSize=10" while actively filtering.

Answer №1

One way to cancel an ajax call is by using the following code snippet

xhrRequest: any;

protected fetchData = (params) => {

if(this.xhrRequest){
    this.xhrRequest.abort();
}

this.xhrRequest = $.ajax({
    method: 'GET',
    url: this.apiUrl,
    data: params.data,
    beforeSend: (request) => {
        request.setRequestHeader('Authorization', `Bearer ${this.authService.getToken()}`);
    }
}).done((response) => {
    params.success(response);
});
}

If you need to cancel the call when a button is clicked, use the following code

onClickButton(){
    if(this.xhrRequest){
        this.xhrRequest.abort();
    }
}

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

What is the best way to transfer my static files to the desired output directory in a TypeScript Express application?

I am attempting to transfer my static files from the input directory to the output directory using Express. I found guidance in this tutorial, which utilized shell.js for copying static files. The code responsible for this operation is located in CopyAsse ...

Is the translation pipe in Angular 5 impure?

I'm currently utilizing ngx-translate. Can you tell me if the translation pipe is considered pure or impure? Also, would it be more beneficial to use the directive syntax translate="X" instead? ...

Angular 2 Service Fails to Retrieve Data with HTTP PUT Request

I am facing an issue with retrieving data from a service. I need to pass an object with specific properties to fetch the data. Although I am passing the object correctly without any errors in the console, the data I assign to the object is empty. Below, I ...

Using a combination of AJAX and PHP, we can create a dynamic text editing feature that allows users

editModal.php <div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true" style="display: none;"> <div class="modal-dialog"> <div class="modal-content"> ...

Oops! It seems like there is an issue with the Renderer2 provider in Angular v 4.1.3

Currently in the process of refactoring one of my services due to a breakage post-upgrade. I had to replace browserdomadapter(); along with several other deprecated methods. As a result of multiple deprecations starting around version 2.1 and various brea ...

Transitioning an AngularJS factory to TypeScript

I'm currently in the process of transitioning an AngularJS application to Angular and one of the challenges I've encountered is converting my JavaScript code to TypeScript. While I've been successful with components and services, factories h ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Tips for sending TypeScript objects to Vue components

Currently, I am working with the Vue 2 composition API plugin along with typescript version 3.9.7. In my project, I have a simple type defined as Usp which I want to pass as a prop to a component named UspSection. The structure of the USP type is outline ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

Encountered an issue when attempting to save data to the database using an AJAX request in Symfony 3

i need to input text in a form and store it in my database as well as display it on my view using jQuery. here is the input form: <div class="panel rounded shadow"> <form method="post"> <textarea id="txt" class="form-control in ...

Issue with parsing string data from API call in Angular (Web Core 3)

Controller code: [Route("api/[controller]")] [ApiController] public class CustomController : ControllerBase { ApplicationDbContext dbContext = null; public CustomController(ApplicationDbContext ctx) { dbContext = ctx; } ...

If placed in the same document, will promises be executed sequentially?

Let's say I have a function in one file that returns a promise: public async a():Promise<string>{ return 'hi' } In another file, I use this function like so: await service.a.then( hi =>console.log(hi)).catch(err=>{throw err}); ...

Unable to properly display data onto view in Ionic 2 (using Angular 2 and TypeScript)

I am facing an issue with Ionic 2. I have a problem where I need to display a card component using *ngFor with the title of an article and other data such as thumbnails, etc. When I hardcode values in the array, the card shows up fine. However, when I use ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...

Error message "The process is not defined during the Cypress in Angular with Cucumber process."

Exploring Cypress for end-to-end testing in an Angular 12 project with Cucumber and TypeScript has been quite the journey. Cypress launches successfully using npx cypress open, displaying the feature file I've created: https://i.sstatic.net/Q5ld8.png ...

Is there a way to access the callback function's arguments and its return value from outside the function?

Is it possible to access both the callback function argument and the return value of a function that takes a callback function as an argument, outside of the function? Consider the following example with a function called func_a. function func_a(callback: ...

How come my ts-mockito spy isn't delegating method calls properly?

In my code, I have a class named MyPresenter which has a method called doOperation(). This method calls another method on a View class that implements an interface and is passed in as a parameter. Below you can find the implementation of the class, interfa ...

Mule - Delivering data from various streams promptly upon availability

Greetings, Stack Overflow community. I have a website where users can input search terms like product names or categories. This data is then sent to Mule ESB to query multiple databases - one being fast with quick results and the other slow, sometimes tak ...

What is the process for developing a type expression that can be reutilized?

Imagine having a pair of functions like the following with identical return types: private isFormArrayOrGroup(formControl: AbstractControl): formControl is UntypedFormGroup | UntypedFormArray How can I create a type that is reusable for formControl is Unt ...

Exploring the relationship between two entities in Angular 7 using Typescript

Creating a Reactive form for user registration in Angular involves setting up the form data object separately from the viewmodel object. https://i.sstatic.net/ERlYa.png export interface RegisterViewModel { UserName: string; Email: string; Password: strin ...