1.步骤一
const requestListMap = new Map()
const CancelToken = axios.CancelToken // 取消请求
/**
* 每一个请求生成一个key
* @param config 请求配置对象
* @returns string
*/
function getRequestKey(config: any) {
const { url, method, params = {}, data = {} } = config
return [url, method, JSON.stringify(params), JSON.stringify(data)].join()
}
/**
* 删除请求key
* @param config
*/
function removeRequestKey(config: any) {
const requestKey = getRequestKey(config)
if (requestListMap.has(requestKey)) {
const cancel = requestListMap.get(requestKey)
cancel() // 取消请求
requestListMap.delete(requestKey)
}
}
/**
* 添加请求key
* @param config
*/
function addRequestKey(config: any) {
const requestKey = getRequestKey(config)
console.log(requestKey)
config.cancelToken = new CancelToken((cancel) => {
if (!requestListMap.has(requestKey)) {
requestListMap.set(requestKey, cancel)
}
})
}
2.步骤二
请求拦截里面添加
removeRequestKey(config) // 删除key
addRequestKey(config) // 添加key
3.步骤三
响应拦截里面添加
removeRequestKey(response.config) // 删除key
4.步骤4
错处抛出里面添加
error.config && removeRequestKey(error.config) // 删除key