Steps for canceling a promise using $resource in AngularJS version 1.5

I am currently using angular 1.5.7 and I am facing an issue where a delete operation on a resource is taking too long to complete. I am working with a MEAN stack and there are times when the delete operation appears to be pending, making me wonder if MongoDB is causing the delay. Here is the code snippet for the factory and the controller where the delete function is being called: * Factory:

      .factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
    return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
      'update': {
        method: 'PUT'
      },
      'delete': {
        method: 'DELETE'
      }
    });
  }])
  • Controller snippet:

    $scope.delete = function (address, addressesList) {
    
    $scope.deleteDisabled=true;
    
    console.log('[ModeratorsCtrl] Deleting:' + address.name);
    console.log('[ModeratorsCtrl] ' + addressesList.length);
    addressesFactory.delete({id: address._id}).$promise.then(
      function (response) {
        $scope.deleteDisabled=false;
        console.log('[ModeratorsCtrl] Address deleted successfully');
      },
      function (response) {
        $scope.deleteDisabled=false;
        var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;
        console.log(message);
      }
    );
    

    };

I came across this post How to cancel $resource requests where they talk about cancelling requests using $cancelRequest() from AngularJS ngResource service, but I am somewhat confused about it. Can someone provide insights into the best practices for cancelling promises in my implementation? Regards,

Answer №1

If your resource is called Users, and you want to cancel the request, make sure to name your action appropriately.

var request = Users.query();

Once you have defined this request, it becomes a promise. To cancel it, all you need to do is,

request.$cancelRequest();

You can then successfully cancel the request.

Answer №2

Appreciate the assistance! Here's what I implemented in my factory:

  .factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
    return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
      'update': {
        method: 'PUT'
      },
      'delete': {
        method: 'DELETE',
        cancellable: true
      }
    });
  }])

And then in my controller:

 $scope.delete = function (address, addressesList) {
    $scope.deleteDisabled = true;//prevent multiple click

    var deleteRequest = addressesFactory.delete({id: address._id});
    deleteRequest.$promise.then(
      function (response) {
        $scope.deleteDisabled = false;
        console.log('[ModeratorsCtrl] Address deleted successfully');
      },
      function (response) {
        $scope.deleteDisabled = false;
        var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;
        console.log(message);
      }
    );

    $timeout(function () {//2 seconds then cancel the promise
      if ($scope.deleteDisabled === true) {
        console.log('[ModeratorsCtrl] Cancel ...');
        deleteRequest.$cancelRequest();
        $scope.deleteDisabled = false;
      }
    }, 2000);
  };

I believe this approach aligns with best practices. Any feedback is welcome!

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

Is it time to use the JavaScript preload() function?

When I initially select a radio button, I experience a brief freezing effect. However, upon selecting them a second time, everything operates smoothly. I suspect this is due to the radio buttons being stored in the browser cache. Is there a way to preloa ...

What is the best way to integrate Greensock CustomEase with TypeScript?

Currently, I am developing a game using Typescript with PixiJS and GreenSock (or is it GSAP?) for handling all the tweening. I recently encountered a situation where I needed to implement some custom easing using cubic-bezier curves. GreenSock provides a C ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

"Utilizing Object.call() in JavaScript for inheritance yields an undefined result

I have been working on implementing an object-oriented approach in my program. According to what I've learned, there should be an inheritance relationship between World and Sprite classes, with Sprite as the parent. However, when I try to call Sprite. ...

Generating a New Form in AngularJs Dynamically from a Separate Input

Within my application, there is a number picker that lets users increase or decrease the value, thanks to Maike Daloo's contribution. Currently, I am exploring ways to iterate through the selected number and generate a form with input fields. This wi ...

Error encountered during Next.js project build: Entry point specified for implicit type library 'build'

While working on my nextjs project, I encountered the following error: Type error: Cannot find type definition file for 'build'. The file is in the program because: Entry point for implicit type library 'build' Can someone guide ...

Could you explain the purpose of the app.use(cors()) function call?

I'm aware that accessing an API with a different domain than our own is not allowed. Nonetheless, I often observe individuals incorporating the cors module into their Express.js applications in order to interact with APIs and then utilizing it in this ...

Steps to access a unique custom drop-down menu in an upward direction

Presently, I am developing a customized AngularJS drop-down feature, which is outlined in the following HTML structure: <div> <label></label> <div> <a ng-class="{active: popover}"> <div></div> <!- ...

Is it a mistake? Using React and ES6 without Babel may not be the

Have you ever considered bundling all of your classes into a single file without using Babel to polyfill it to ES5? If the browser doesn't support ES6, you could then use Babel in the browser or load the polyfilled bundle and manually add the dependen ...

Tips for initiating a browser file download using JavaScript, ensuring that the download is only carried out if the web service responds with

For a project I am working on, I need to create JavaScript code that will be triggered by clicking on an <a> element. This code will then make a GET request to a web service that I am currently in the process of coding. Once the service returns a fil ...

Is there a way to hide the thumbnail image when the title is hovered over without using CSS?

I'm currently using a simple jQuery script to switch between two thumbnails when hovering over a div. The code works perfectly for the .thumbs class, but I also want this functionality to work with the post titles. Unfortunately, adding the .headline ...

Empty Array result from push operations during Node.js/Express GET request

Currently, I am in the process of coding a function that involves calling an API to fetch URLs. Below are the specific steps I aim to achieve: Take in an array of objects (specifically restaurants) as input Initiate a call to the Google Search API for ea ...

What is the best way to switch focus to the next input using jQuery?

Currently, I am implementing the autocomplete feature using jQuery and everything seems to be functioning properly. The only issue I've encountered is with Internet Explorer (IE) - when a user selects an item from the autocomplete list, the focus does ...

The functionality of onClick and console.log seems to be malfunctioning on Nextjs

I'm currently learning NEXT but I've encountered some issues with certain functions "use client" import { useState } from 'react' export default function idk() { const [counter,setCounter]=useState(0) const add=()=> ...

What is the best way to pass parameters from a Spring controller to an AngularJS module for rendering on a JSP page?

I am attempting to pass a parameter in the following manner: Within my Spring controller, mynamePage.java @RequestMapping(value = "/myname", method = RequestMethod.GET) public String mynamePage(ModelMap model) { model.addAttribute("myname", "eloy"); ...

stop the leakage of CSS and JS from the subtree to the document through the inverse shadow DOM mechanism

My page contains dynamic HTML content that I want to incorporate. The dynamic content consists of only HTML and CSS, without any JavaScript. However, I have some custom global CSS styles and JS logic that need to be implemented along with this dynamic con ...

Clearing all data in a form upon opening

Within a single portlet, I have organized two forms under separate tabs. What I am aiming for is that whenever I switch to tab 2, all fields within its associated form should automatically be cleared without the need for a button click. Even after attempti ...

The behavior of the Bootstrap toggle with a chevron varies between the production environment and the local

For my Bootstrap accordion menu, I used a trick where the chevron turns upside down when clicked on the toggle. You can check out the trick here. In the example, the chevron is pulled to the right. When I implemented this on my website locally, the chevr ...

What is the best way to retain the leading zeros when creating a new Number() in JavaScript?

Hey everyone, I'm running into some issues with this specific function. const incrementString = str => { if (!str.match(/[\d+]$/)){ return str += 1 } else{ return str.replace(/[\d+]$/, match => new Number(match) + 1) } ...

Exploring Laravel's method for retrieving data from multiple tables in the controller

In an effort to make my jQuery call more dynamic, I have a controller with the following method: public function api(Request $request , $project_id){ return Program::where('project_id',$project_id)->get(); } This results in: [{"id":178," ...