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

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...

Having trouble with the page redirection issue? Here's how you can troubleshoot and resolve

My goal is to restrict access to both the user home and admin dashboard, allowing access only when logged in. Otherwise, I want to redirect users to the login or admin login page. import { NextResponse } from 'next/server' import { NextRequest } ...

Enhance Bootstrap typeahead to accommodate multiple values

I have a basic typeahead setup for searching city names. However, upon selecting a city, I also need to retrieve its latitude and longitude in order to send that data to the backend. $('.typeahead').typeahead({ minLength : 3, source : ...

Utilizing a React Hook to set data by creating a pure function that incorporates previous data using a thorough deep comparison methodology

I have come across the following code snippet: export function CurrentUserProvider({ children }) { const [data, setData] = useState(undefined); return ( <CurrentUserContext.Provider value={{ data, setData, }} & ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...

Modify the values in a textbox using JavaScript to suit your needs

unusual issue: I'm encountering a strange bug with my form. I have an ajax datepicker attached to a text box, but when I submit the form, all values are received except for those from the datepicker checkboxes. Why is the .Text property empty for th ...

When using jQuery AJAX to Like/Dislike, a 500 (Internal Server Error) is returned, but the functionality works correctly upon reloading the

My website has a feature where users can press a Like Status button that uses AJAX to send data to the controller. When the button is clicked, it changes from "like" to "dislike" and all associated classes and form actions are updated accordingly. The is ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

New to React and looking for guidance on implementing .forEach or .includes in my code

My task involves going through an array and checking if a string that the user inputs into the form exists in it. This can be achieved using forEach or .includes method. I am basically trying to filter out the array based on the input. If someone could de ...

In Javascript, the color can be changed by clicking on an object, and the color

Looking for help with my current HTML code: <li><a href="index.php" id="1" onclick="document.getElementById('1').style.background = '#8B4513';">Weblog</a></li> The color changes while clicking, but when the lin ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Struggling to send data to Wufoo API using PHP and AJAX

I'm still getting the hang of PHP and attempting to send data to a Wufoo Form that includes the fields shown below: However, when trying to POST information to it, I keep receiving a 500: Internal Server Error along with an 'Uncaught SyntaxError ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

Unlock the ability to retrieve the current Ember route directly within a component

I have a unique custom Ember component embedded within a controller. Currently, I am attempting to dynamically retrieve the name of the current route. In order to access the controller, I use: this.get('parentView') However, I am facing diffi ...

obtain the final result once the for loop has finished executing in Node.js and JavaScript

There is a function that returns an array of strings. async GetAllPermissonsByRoles(id) { let model: string[] = []; try { id.forEach(async (role) => { let permission = await RolePermissionModel.find({ roleId: role._id }) ...

Getting data from a response in Express.js involves using the built-in methods provided by

I am a beginner at Node.js and I'm currently experimenting with client-server communication. Below are the codes I've been working on: server: app.post('/zsa', (req, res) => { res.send("zsamo"); }); client: fetch(&qu ...

Using the AngularJS directive with $http to handle JSON responses

Following the steps mentioned here I am using Ajax to retrieve server data which is in Json format containing markup with a directive. I am attempting to use $compile to trigger this directive, but so far, I have been unsuccessful. Below is the controlle ...

I've been struggling with this javascript error for three days, how can I finally resolve it?

Currently developing a website using react js, but encountering an error every time I try to push to my github repository. Run npm run lint npm run lint shell: /bin/bash -e {0} <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...