Stop or abort any pending API requests in Restangular

I am currently working with an API service:

var SearchSuggestionApi = function (Restangular) {

  return {
    getSuggestion: function (keyword) {
      return Restangular.one('search').customGET(null, {keyword:keyword});
    }
  };

};

SearchSuggestionApi.$inject = [
  'Restangular'
];

In order to call this API, I have created a controller:

vm.getSuggestion = function (keyword) {

  SearchSuggestionApi.getSuggestion(keyword)
    .then(
      function (data) {
        vm.listData = data;
      }, function (error) {
        console.log(error);
      });
};

My issue arises when I make multiple calls to vm.getSuggestion(keyword), specifically more than once. For example:

vm.getSuggestion('a'); // => Returns an array with multiple objects
vm.getSuggestion('a b');// => Returns an empty array

Since vm.getSuggestion('a') returns a lot of data, it completes after vm.getSuggestion('a b'). This results in vm.listData containing [{object1}, {object2}, ...], but I want vm.listData to be [] (the response data from the last function).

Is there a way to cancel pending API calls in the first function when calling the second function, or any other methods to get the last response data and set it for vm.listData?

I have looked into some articles about cancelling pending API calls, but they did not provide a solution to my specific problem.

Thank you for your assistance :)

Answer №1

Here are a few different approaches to tackle this issue:

  • In your then callback, you can verify if the received value is still relevant before proceeding:

    vm.getSuggestion = function (keyword) {
    
      SearchSuggestionApi.getSuggestion(keyword)
        .then(
          function (data) {
            if (vm.keyword === keyword) {
                vm.listData = data;
            }
          }, function (error) {
            console.log(error);
          });
    };
    
  • You can also stop the request by setting a timeout promise

  • If you encounter this issue frequently, consider replacing the promise with an RxJS observable stream along with appropriate operators. Although it requires an extra library, it offers a more organized solution.

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

Conceal DIV containers during the loading of the page, and reveal them only upon the selection of Radio Buttons

In my user interface, I have implemented three radio buttons labeled as "Easy," "Medium," and "Hard." Each button is assigned to a distinct Javascript function that manipulates the visibility of corresponding div elements. The main purpose behind this setu ...

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

My component fails to load using Angular Router even though the URL is correct

I have been experiencing an issue while trying to load my Angular component using the router. The component never appears on the screen and there are no error messages displayed. app-routing-module { path: '', redirectTo: '/home', ...

Installing npm displays the command for the successfully installed module, yet no new files are generated

After adding rx-angular to my npm package and successfully installing it locally, I encountered some issues when trying to release it to production. It seemed to partially work but not entirely, leading to confusion due to errors that prompted me to manual ...

Effects of jQuery Show / Hide on adjacent select box operations

I created a pair of select boxes where the visibility of one is controlled by the other. Initially, the controlled select box (#select02) works perfectly on page load as long as I don't show/hide it by selecting options in the controlling select box ( ...

What is the best way to ensure a function waits for a stable database connection before proceeding?

Perhaps not phrased well, but I grasp the concepts of async/promises/callbacks. My aim is to develop a module that can be imported (database.js), where I can then execute methods like database.insert() and database.read(). This is the code I have so far: ...

Node.JS program unexpectedly logging MySQL results to console and exhibiting erratic behavior

Recently, I encountered a peculiar error while working with Node.JS MySQL. Strangely, I noticed that a result was being logged in the console without any corresponding code line instructing it to do so. Even more baffling was the fact that when I intention ...

Success callback for tracking conversions on Google

When an ajax call is successful, I am triggering the Google conversion tracking code. Along with tracking the conversion, I also need to change the window location. Is there a method to receive a callback when the conversion tracking is successful, so tha ...

Steps to correctly reset an XMLHttpRequest object

I'm currently working on a project where I send AJAX requests, receive responses, and replace text based on those responses. However, it seems like I may be missing a fundamental concept in my approach. request.onreadystatechange = () => { if (r ...

Restricting or postponing HTTP requests in an AngularJS service

I recently developed a service for my AngularJS app that retrieves data by making $http calls through various methods. However, I encountered an issue where these requests were being triggered every time an HTML element in the view (a product details div) ...

NodeJS not recognizing global variable causing it to return undefined

Can a global variable be defined in a node.js function? I wish to use the variable "ko" (declared in the getNumbers function) in other functions function getNumbers(callback) { result = cio.query("SELECT numbers FROM rooms WHERE durum='1'", ...

Customizing MUI DataGrid: Implementing unique event listeners like `rowDragStart` or `rowDragOver`

Looking to enhance MUI DataGrid's functionality by adding custom event listeners like rowDragStart or rowDragOver? Unfortunately, DataGrid doesn't have predefined props for these specific events. To learn more, check out the official documentati ...

The error "Cannot invoke the indexOf method on an undefined element at order" is being encountered in Javascript

Looking for assistance with creating a function to sort a string where each word contains a single number from 1 to 9 (no 0). For instance, given the input: "is2 Thi1s T4est 3a", the desired output should be "Thi1s is2 3a T4est". The current code snippet ...

In Chrome version 69.0.3497.100, material design does not display dynamic elements off the screen

STACK: react: 16.8.6 redux: 4.0.1 DESCRIPTION: When using $compile to dynamically add elements on a page, I encountered an issue in Firefox (76.0) where input elements that are out of the screen are not rendered. Only the labels are displayed. view image ...

How can we organize and display the data from two linked arrays, one containing player names and the other containing

Looking for help on how to rank 3 players based on their scores using arrays. I've hit a roadblock and need guidance! Here's a brief example: Player 1 : Taylor Score Taylor : 15 Player 2 : Jordan Score Jordan : 20 Player 3 : Alex Score Alex : ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

Problem with autocomplete functionality in Angular Material's md-contact-chips

Having some trouble with the autocompletion feature of md-contact-chips. I want to capture the $query as soon as someone starts typing. HTML <md-contact-chips ng-model="members" md-contacts="querySearch($query)" md-contact-name="fullname" ...

Changing the `$location.path` updates the URL without triggering a redirect

When I try to redirect to another page by clicking a button or a link, the URL changes but the redirection doesn't happen. I have to manually refresh the page with the new URL. I'm not sure if the issue lies in the module or the controller. loca ...

Is it possible to conceal JavaScript comments on a page before it is displayed?

Curiosity has led me to ponder a question that may seem trivial. Consider this scenario: in my HTML or ASPX page, I include a comment for some JavaScript code. When the page loads, will the comments be rendered along with the rest of the page's conten ...