简体   繁体   English

进行多个api调用时如何选择最新的api调用

[英]How to pick latest api call when multiple api call were made

We ran into a problem when multiple API calls were made repeatedly the UI sometimes renders the wrong data. 当重复进行多个API调用时,我们遇到了一个问题,UI有时会呈现错误的数据。

Example: 例:

onPageLoad event I have 5 API calls and we have date picker from where we can select the dates. onPageLoad事件我有5个API调用,并且有日期选择器,可以从中选择日期。 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). 当用户尝试更改日期选择器时,将进行所有5个API调用以刷新数据,假设最初我是在上一天选择的,并且页面已加载,现在我更改为上周,然后是一个月,然后又回到了最后一天,现在有15个异步进行了API调用,并且在UI中,我们渲染了最近到达的任何API调用(由于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. 在上面的示例中,我只想在UI中显示最新的API调用数据(无论何时解决承诺),我只想显示前一天的数据。

With this code any previous api call will be rejected. 使用此代码,任何先前的api调用都会被拒绝。 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});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM