0

We ran into a problem when multiple API calls were made repeatedly the UI sometimes renders the wrong data.

Example:

onPageLoad event I have 5 API calls and we have date picker from where we can select the dates. When user tries to change the date selector all the 5 API calls will be made to refresh the data suppose initially I selected last day and the page is loaded and now I changed to last week then month and then back to last day now there 15 async API calls were made and in the UI we are rendering whichever API call arrived the lately(because of Asynchronous behaviour in JS). Is there any mechanism in angular to control this behavior.

Expected:

I want to show only the latest API call data in the UI(irrespective when the promise gets resolved) in the above example I want to show only last day's data.

Community
  • 1
  • 1
  • I handled a similar problem saving the last api call timestamp client-side and sending it along the other parameters just to be returned by the api. By doing this you will just have to confront the values and keep the api response with the last timestamp. – cornacchia Jul 06 '18 at 10:41
  • Even i tried that approach but the problem exists some parts of the page might be with oldest api call still Ex: i have made 1, 2, 3 api call i made and i got the response in the order as 1, 3, 2 then am showing response 2 in the UI. – Lakshmana Gumpina Jul 06 '18 at 11:02
  • Sure @BuhBuh am new here will learn :-) – Lakshmana Gumpina Jul 06 '18 at 11:25

1 Answers1

0

With this code any previous api call will be rejected. This means only the last call will resolve.

var timeout;

function callApi() {
    // Cancel any previous api call:
    timeout && timeout.resolve();

    // Create a new timeout:
    timeout = $q.defer();

    // Make the api call, passing in the timeout:
    return $http.get('/api', {timeout: timeout.promise});
}
Buh Buh
  • 7,443
  • 1
  • 34
  • 61
  • Since we are passing the new timeout obj in every request the server may not able to leverage the caching functionality and other thing is if i have more than one api call(diff URI) then do we need to maintain separate timeout objects? – Lakshmana Gumpina Jul 06 '18 at 11:39
  • Yes, a different timeout variable for each type of api call. You could use a factory method to help you generate that. As for cacheing, I'm not sure what you mean exactly. I don't know what apis you are calling so it is hard for me to know what kind of cacheing you need. – Buh Buh Jul 06 '18 at 12:01