知道 axios 中是否有待处理的请求 [英] Know if there are pending request in axios
问题描述
我是 ReactJS 的新手,对于我的 ajax 调用,我尝试使用 Axios 库.太棒了,但现在我想知道是否有办法知道 axios 拦截器中是否有待处理的请求,因为我想显示每个 ajax 调用的加载覆盖(如果它尚未可见)并在 ALL 时删除覆盖承诺已解决.现在我从拦截器开始开发:
I'm new in ReactJS and for my ajax call I tried to use Axios library. It is awesome, but now I would like know if there is a way for know if there are pending requests in axios interceptor because, I would like, show loading overlay every ajax call (if it is not yet visibile) and remove overlay when ALL promise are resolved. For now I developed start with interceptor:
axios.interceptors.request.use(function (config) {
//here logi of show loading
return config;
}, function (error) {
return Promise.reject(error);
});
我想添加如下内容:
axios.interceptors.respose.use(function (config) {
//logic remove loading if it is last response
return config;
}, function (error) {
return Promise.reject(error);
});
那么如何(如果可能)知道它是否是最后的响应?在使用 ReactJs 之前,我使用了 Angular 1.x 并且在 $http service
中有
So how, (if it is possibile) know if it's last response?
Before using ReactJs, I used Angular 1.x and in $http service
there was
$http.pendingRequests
axios 中有类似 $http 的服务吗?
There is in axios something like $http service?
推荐答案
这是我的解决方案 :)
This was my solution :)
var numberOfAjaxCAllPending = 0;
// Add a request interceptor
axios.interceptors.request.use(function (config) {
numberOfAjaxCAllPending++;
// show loader
return config;
}, function (error) {
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
numberOfAjaxCAllPending--;
console.log("------------ Ajax pending", numberOfAjaxCAllPending);
if (numberOfAjaxCAllPending == 0) {
//hide loader
}
return response;
}, function (error) {
numberOfAjaxCAllPending--;
if (numberOfAjaxCAllPending == 0) {
//hide loader
}
return Promise.reject(error);
});
这篇关于知道 axios 中是否有待处理的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!