場景:當我們在發出請求后佇列里有多個請求的時候,大幅度的消耗了后端的資源,進行了很多不必要的操作,
解決:在請求攔截器中,添加去查找當前請求佇列里相同的域名介面,如果有,洗掉當前請求,回傳上一個請求,
實體:
let pending = []; //宣告一個陣列用于存盤每個ajax請求的取消函式和ajax標識
let removePending = config => {
for (let p in pending) {
if (
pending[p].u === config.url + "&" + config.method &&
!noCancelUrlList.includes(config.url.replace(baseURL, ""))
) {
//當當前請求在陣列中存在時執行函式體
pending[p].f(); //執行取消操作
pending.splice(p, 1); //把這條記錄從陣列中移除
}
}
};
//添加請求攔截器
axios.interceptors.request.use(
config => {
removePending(config); //在一個ajax發送前執行一下取消操作
config.cancelToken = new cancelToken(c => {
// 這里的ajax標識我是用請求地址&請求方式拼接的字串,當然你可以選擇其他的一些方式
pending.push({ u: config.url + "&" + config.method, f: c });
});
return config;
},
error => {
return Promise.reject(error);
}
);
//添加回應攔截器
axios.interceptors.response.use(
response => {
if (response.data.code == 0 || response.data.type == 'FeatureCollection') { //請求成功或者為本地資料時回傳,否則攔截
removePending(response.config);
//在一個ajax回應后再執行一下取消操作,把已經完成的請求從pending中移除
return response;
} else if (response.data && !response.data.code) {
//資料流獲取過濾
removePending(response.config);
return response;
} else {
Message.error(response.data.errorMsg);
if (response.data.code == 1) {
window.location.href = "#/login";
}
}
},
error => {
return {
data: {
code: 666,
cancel: true,
errorMsg: "請求已關閉"
}
};
}
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/279289.html
標籤:其他
上一篇:android安卓開發-自由移動組件SimpleMovingView-自定義View繪制組合控制元件系列
下一篇:Codeforces Round #717 (Div. 2) C. Baby Ehab Partitions Again
