axiosProgress.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import iView from "iview";
  2. import axios from "axios";
  3. const calculatePercentage = (loaded, total) => Math.floor(loaded * 1.0) / total;
  4. export function loadProgressBar(instance = axios) {
  5. let requestsCounter = 0;
  6. const setupStartProgress = () => {
  7. instance.interceptors.request.use(config => {
  8. requestsCounter++;
  9. iView.LoadingBar.start();
  10. return config;
  11. });
  12. };
  13. const setupUpdateProgress = () => {
  14. const update = e =>
  15. iView.LoadingBar.update(calculatePercentage(e.loaded, e.total));
  16. instance.defaults.onDownloadProgress = update;
  17. instance.defaults.onUploadProgress = update;
  18. };
  19. const setupStopProgress = () => {
  20. const responseFunc = response => {
  21. if (--requestsCounter === 0) {
  22. iView.LoadingBar.finish();
  23. }
  24. return response;
  25. };
  26. const errorFunc = error => {
  27. if (--requestsCounter === 0) {
  28. iView.LoadingBar.error();
  29. }
  30. console.log(error);
  31. throw error;
  32. };
  33. instance.interceptors.response.use(responseFunc, errorFunc);
  34. };
  35. setupStartProgress();
  36. setupUpdateProgress();
  37. setupStopProgress();
  38. }