Stop or terminate all ongoing requests in AngularJS

When switching routes, I want to prevent any pending requests from the previous route in order to avoid issues where responses from the previous route interfere with data on the current route. This sometimes happens when responses from the previous route take a long time to complete.

I am considering using an http interceptor for this purpose:

$httpProvider.interceptors.push(function($q) {
    return {
     'request': function(config) {

      },

      'response': function(response) {

      }
    };
  });

In the request function, I could update the config.timeout with a promise as suggested here, and store all deferred objects in a global cache so they can be cancelled collectively.

However, one issue with this approach is that it might overwrite config.timeout settings made elsewhere in the codebase.

Another potential solution could involve cancelling all AJAX requests at the XMLHttpRequest level, but I am unsure how to implement this. Any recommendations or advice would be greatly appreciated. Thank you.

Answer №1

It's clear that the timeout API is currently our best option for canceling a running $http request. Using an interceptor along with a cancel promise seems to be a good approach.

An idea could be to attach the complete deferred object to the $http request and then cancel all pendingRequests in your route change handler.

This code snippet might do the trick:

angular.module('module').config(function ($httpProvider) {
  $httpProvider.interceptors.push(function ($q) {
    return {
      request: function (config) {
        if (!config.timeout) {
          config.cancel  = $q.defer();
          config.timeout = config.cancel.promise;            
        }

        return config;
      }
    }
  });
});

angular.module('module').run(function ($rootScope, $http) {
  $rootScope.$on('$stateChangeStart', function () {
    $http.pendingRequests.forEach(function (pendingReq) {
      if (pendingReq.cancel) {
        pendingReq.cancel.resolve('Cancel!');
      }
    });
  });
});

There are no guarantees this will work perfectly, but I've had some success with it. It's often tough to find a one-size-fits-all solution for these cases.


edit

If you encounter issues with the error handler of the cancelled promise, you can utilize the responseError property and make adjustments there.

angular.module('module').config(function ($httpProvider) {
  $httpProvider.interceptors.push(function ($q) {
    return {
      responseError: function (response) {
        if (response.config.timeout.$$state.value === 'Cancel!') {
          // debugger; 
          return $q.when('bypassed');
        }
      }
    }
  });
});

It appears that finding a perfect solution to achieve your desired outcome may be elusive. Sometimes we have to navigate through unconventional territory : )


edit2:

I'm currently testing the above method myself. By using $q.when('something') in the responseError, you can effectively bypass the error callback of the cancelled $http request. Let me know if this solution works for you.

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

Node Js seems to be taking quite a while to output to the console

Hello, this is my first time posting on Stack Overflow so please bear with me if I make any mistakes. I created a button that, when clicked, decrements the quantity by one. After updating the UI, I send the data to the server. However, when I console log t ...

Troubleshooting Issues with Form Inputs in JS/Angular Using Places API and document.getElementById Method

I have integrated the Google Places API to automatically populate locations/destinations into a form after a user searches. The auto-population works correctly, but I am facing an issue when trying to submit the form into my database – the object is alwa ...

What is the best way to implement data validation for various input fields using JavaScript with a single function?

Users can input 5 numbers into a form, each with the same ID but a different name. I want to validate each input and change the background color based on the number entered - red for 0-5, green for 6-10. I wrote code to change the color for one input box, ...

Show the JSON response from the controller on the view page

In my controller, I have a JsonResult action that returns a list of House objects. My goal is to retrieve this data onclick using ajax and display the JSON data within my view. While I can see the proper response and JSON result in Firebug, I'm not su ...

Switching from the global import module pattern to ES6 modules

In recent years, my approach to JavaScript development has involved using the global import method. Typically, I work with a set of utility functions packaged and passed to a separate site module containing individual functions for each web functionality: ...

How to Extract Minutes in Datatables Timestamps and Apply Custom Styling

Working with Datatables v1.10 Right now, my table is showing a date in the second column in the format 17-04-2019 14:34, which is how it's stored in the database. The filtering and searching functionality are all working as expected. The current HTM ...

The ExpressJS application encountered an error while processing the Google API response: a required parameter

I'm currently using ExpressJS and trying to fetch data from the Google Books API. I've set up a test request to access : const express = require('express'); var request = require('request'); const auth = require('../midd ...

Exploring the world of WebSockets and Socket.io

Recently many online games, like , have started using WebSockets to create real-time MMORPGs. I'm curious about how to develop a node.js program that can manage connections from browsers using WebSockets. Here is an example of browser code: <!DOC ...

Creating a POST method in AngularJS

Here is the code snippet I am working with: var req = { method: 'POST', url: '/customer', headers: { 'Content-Type': 'application/json' }, data: { test: 'testvalue' } }; $http(re ...

CSS Class Not Updating in WordPress Using JavaScript

Looking to incorporate a small JavaScript code directly into The Twenty Sixteen theme in WordPress. This HTML Code needs to be modified on the Page: <p class="site-description">Example Text</p> The goal is to change a classname: document.g ...

Issue with Ionic and Angular: Struggling to empty input field

Within my Ionic app, there is a form that contains an input field and a button. Upon clicking the button, an action should occur within the controller to clear the input field. Unfortunately, this functionality is not working as expected. Despite its simpl ...

I have been unable to find a solution for the non-functioning jQuery (3.4.1 / 3.3.1) load() issue

I have been working with jQuery's .load() function Take a look at my code snippet: <html> <head> <meta charset="utf-8"> <title>load demo</title> <script src="https://code.jquery.com/jquery-3.4.1.js"> ...

Learn how to toggle the display of a div using jQuery, just like the functionality on the popular website

Visit Mashable here Below is the script I am currently using: $(document).ready(function(){ $(".show_hide5").mouseover(function(){ $('.selected').removeClass('selected'); $(this).next().fadeIn("slow").addClass(&apo ...

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

Troubleshooting drag-and-drop functionality in a JavaScript HTML5 application resembling a Gmail upload interface

Here is a snapshot of my user interface: Each node in the tree structure is represented by an <li> element along with an <a> link. Furthermore, each folder serves as a dropzone for file uploads similar to the drag-and-drop feature found in Gm ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Tips for successfully passing an object via a Link

I am trying to pass an object through a Link component in react-router v6. Can someone please guide me on how to achieve this? Below is a snippet of my code where the user should be directed to another component. import React from 'react' import ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...