Having difficulty in terminating the $resource request

Despite attempting various solutions, such as the one mentioned in this thread, I am still unable to successfully cancel a request made using $resource. My latest attempt looks like this:

Controller:

angular.module('theApp')
  .controller('homeController', function ($q, foodTypeFactory) {
    var vm = this;

    vm.testButton = function () {
      vm.aborter = $q.defer();
      foodTypeFactory(vm.aborter).getTest({}, function (data) {
        console.log(data);
      });
    };
    vm.cancelButton = function () {
      vm.aborter.resolve();
    }
  });

foodTypeFactory:

angular.module('theApp')
  .factory('foodTypeFactory', function ($resource, BACKEND_API) {
    return function (aborter) {
      return $resource(BACKEND_API + '/api/foodtypes/:id', {id: '@id'}, {
        getTest: {
          timeout: aborter.promise
        }
      });
    }
  });

Even after trying to cancel the request, it still goes through and completes. I'm working with Angular version 1.6.2 and angular-resource 1.6.2.

What could be the issue here?

Answer №1

My recommendation to you is to implement an http interceptor, which allows you to intercept and control requests. Here's an example of how you can do this:

1) Start by creating a file named auth.interceptor.js:

"use strict";

angular
.module("demo")
.factory('authInterceptorService', ['$q', '$location', 'localStorageService',
function ($q, $location, localStorageService) {
    // Public Method
    return {
        request: function (config) {
            config.headers = config.headers || {};

           if(!MYCONDITION){ //<-- Add your logic here to determine if the request should be terminated
            return; //<-- TERMINATE IT ..
           }else{
            return config; //<-- CONTINUE WITH NORMAL REQUEST
           }


        }
    };
}]);

2) In your app.config.js file:

 $httpProvider.interceptors.push("authInterceptorService");

By adding this interceptor, the logic will be applied to all your requests made using $http or $resource. You can also include injection of the Bearer Token if needed.

I hope this information proves helpful for you.

Answer №2

At last, a solution has been discovered! Starting from angular version 1.5, it is possible to terminate a $resource request using $cancelRequest(). This method was particularly useful in my specific situation:

Controller:

angular.module('theApp')
  .controller('homeController', function (foodTypeFactory) {
    var vm = this;

    vm.testButton = function () {
      vm.onGoingRequest = foodTypeFactory.getTest({}, function (data) {
        console.log(data);
      });
    };
    vm.cancelButton = function () {
       vm.onGoingRequest.$cancelRequest();
    }
  });

foodTypeFactory:

angular.module('theApp')
  .factory('foodTypeFactory', function ($resource, BACKEND_API) {
      return $resource(BACKEND_API + '/api/foodtypes/:id', {id: '@id'}, {
        getTest: {
          cancellable: true
        }
      });
  });

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 to extract a property name from an object in JavaScript without using quotation

I currently have an object that resembles the following: const obj = { id: 1, name: { "english-us": "John", "english-uk": "John", "italian-eu": "Giovanni", }, }; My goal is to c ...

Guide on correctly accessing an attribute in AngularJS directive validators

Currently, I am working on a validator that validates dates in the format of MM/YYYY. However, I am struggling to figure out how to access an attribute every time the model changes: <input id="my-date" validate-short-date data-max-date="{ ...

Modifying data on the fly in Angular

I attempted to dynamically modify my data without continuously requesting it from the server. Below is the code snippet I am currently using: $scope.total_earned = () => { //ng-click function from frontend splice(); loadChartData(1); } ...

Tips for preventing countdown from resetting when you refresh the page

I'm currently using a countdown feature on my Shopify website that is functioning well, except for one issue - whenever the page is refreshed, the countdown resets itself. Can anyone provide guidance on how to solve this problem? Thank you in advance! ...

Transform one column into several columns

I am working with a function that populates a table row by row. Here is the code: function renderListSelecoes(data) { // JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one') va ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

Troubleshooting React Testing Library: Input Field Fails to Update Value During Testing

I'm currently working on a unique React component that wraps an Office UI Fabric TextField within a Formik form. Despite adhering to standard practices for managing input fields with React and Formik, I've come across issues while testing the com ...

Retrieve the sibling files of a newly created file within a Firebase Cloud Function that is triggered by the onFinal

I'm in need of some guidance with a cloud function I have set up that triggers whenever a new file is created in Firebase storage. Within this function, I am looking to gather all other files located at the same path and store them in an array. Howeve ...

Establish a callback function for opening a fresh window using JavaScript

Is there a simple method to assign a "callback" function to a new window opened in javascript? My goal is to execute a function from the parent window in the new window, but I want the parent to be able to specify the name of this specific function (withou ...

Differences between AsyncData and nuxtServerInit

I currently have cookies set up for authorization user and user token. On each nuxtServerInit, I check the cookies for the same data and save them to the store. However, when using asyncData on certain pages, it seems like the asyncData function runs bef ...

A method for cycling through parent and child objects in JavaScript (Vue.js) and storing them in an array - how to

I have a JSON object structured like this. const jsonData = { "id": "6", "name": "parent", "path": "/", "category": "folder", "fid": "6", "children": [ { ...

Generating an Array of objects through the use of the each method

Currently, I am in the process of developing a web scraper using node.js along with puppeteer and cheerio. Although I can successfully display the desired strings in the console.log, I am facing challenges in determining if this task is achievable. $(&apo ...

Understanding the distinctions among variables in typescript

Can someone explain the difference in Typescript between "!option" and "option"? It seems like they are not equivalent. const limit = !options.limit || options.limit === NaN ? 0 : options.limit ...

Mastering the Rejection of Promises in Javascript with Graceful Elegance

One effective pattern using ES2017 async/await involves: async function () { try { var result = await some_promised_value() } catch (err) { console.log(`This block will be processed in a reject() callback with promise patterns, which is far mo ...

Can anyone guide me on how to retrieve a popup validation message on a webpage using Selenium with Python?

Is there a way to use Selenium Python to trigger the popup validation message "Please tick this box if you want to continue" shown in the image? <input oninvalid="this.setCustomValidity('Please tick this box if you want to proceed')" onin ...

Verifying a user's initial visit status using COOKIES in a Servlet

Is there a method to determine if a user is visiting a page for the first time using SERVLET and cookies, without utilizing sessions? I understand how to accomplish this with sessions, but I am specifically looking for a solution that involves only cooki ...

Positioning JQuery tooltips

I've been developing a simple tooltip tool (check out the fiddle link below), but I'm encountering some issues with positioning. My goal is to have the tooltip appear centered and above the clicked link, however right now it appears at the top le ...

Using a JavaScript variable within an Angular component: a step-by-step guide

I am currently working with some javascript code for mapbox in my .ts file within an angular component. My goal is to access a variable called polygonCoordinates[] from the javascript code and use it in my typescript code. Unfortunately, I'm facing di ...

jQuery is producing an incorrect HTML string that includes `="` instead of just `"`

Currently, I am in the process of developing a math task web page and I am facing an issue with setting up dynamically generated buttons. The problem lies in my code generating '=" instead of " on the HTML page. function generateButton(id){ var b ...

Instructions on utilizing sockets for transmitting data from javascript to python

How can I establish communication between my Node.js code and Python using sockets? In a nutshell, here is what I am looking for: Node.js: sendInformation(information) Python: receiveInformation() sendNewInformation() Node.js: receiveNewInformation( ...