Cancel pending API calls in Restangular

Issue

I have API service:

var SearchSuggestionApi = function (Restangular) {

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

};

SearchSuggestionApi.$inject = [
  'Restangular'
];

I have controller to call this API:

vm.getSuggestion = function (keyword) {

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

My problem is when I call vm.getSuggestion(keyword) two or many time (must call than one time). Such as:

vm.getSuggestion('a'); // => Return a array with many object in this
vm.getSuggestion('a b');// => Return empty array

Because vm.getSuggestion('a') return many data, it will finish after vm.getSuggestion('a b'). So vm.listData is [{object1}, {object2}, ...], but I want to vm.listData is [] (response data of the last function).

How can to cancel pending API call in first function when I call seconds function or another ways to get the last response data and set for vm.listData.

I researched some articles about cancel pending API calls, but it not help me about my problem.

Thanks for your help 🙂

Solution

There are various ways of solving this:

  • You can simply check in your then callback whether the value received is still current:

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

  • If you are solving this problem often, you might wish to replace the promise by an RxJS observable stream with the appropriate operators. This is the cleanest solution, but does require an additional library.

Answered By – meriton

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.