知道axios中是否有待处理的请求 [英] Know if there are pending request in axios

查看:188
本文介绍了知道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?

推荐答案

这是我的解决方案:)

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆