itsource

Axios를 사용하여 Vue.js에서 여러 API 호출 취소

mycopycode 2023. 1. 8. 14:38
반응형

Axios를 사용하여 Vue.js에서 여러 API 호출 취소

각각 독자적인 API 호출이 있는 여러 개의 '모듈'이 있는 대시보드를 만들고 있습니다.대부분의 엔드포인트는 재빠르지만 몇 초 정도 걸릴 수 있습니다.

날짜 범위에 대한 필터링 옵션이 있으며 변경 시마다 데이터에 대한 API 호출을 다시 실행합니다.

문제는 사용자가 다른 사용자가 로드하기 전에 날짜 범위를 빠르게 변경할 경우 API 호출을 쌓지 않았으면 한다는 것입니다.

단일 파일 vue 컴포넌트를 사용하고 있으며, 각 API 호출에 대한 메서드와 이들을 그룹화하고 호출하는 단일 메서드가 있습니다.

watch: {
    dateFilter: function() {
        this.initStatModules();
    }
},
methods: {
    getCustomers: function() {
        var $this = this;
        return axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/customers?date=${$this.dateFilter}`).then(function(response) {
            $this.customers = response.data;
        });
    },
    getBookings: function() {
        var $this = this;
        return axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/bookings`).then(function(response) {
            $this.bookings = response.data;
        });
    },
    getTotalRevenue: function() {
        var $this = this;
        return axios.get(`/api/v1/reports/${$this.team.id}/services-revenue?date=${$this.dateFilter}`).then(function(response) {
            $this.totalRevenue = response.data.data.totalRevenue;
        });

    },
    initStatModules: function() {
        this.getCustomers();
        this.getBookings();
        this.getTotalRevenue();
    }
}

watch 또는 initStatModules 메서드에서 보류 중인 API 요청을 모두 취소했으면 합니다.

axios documents: https://github.com/axios/axios#cancellation 를 보면, 서포트되고 있습니다만, 원하는 대로 실장하는 방법을 이해할 수 없습니다.

감사합니다!

Axios는 "콜을 취소하는 것이 아니라 콜을 회피하는 것이 좋다"고 말했다.

내가 의미하는 것은:

필터 콜이 발생하고 있는 경우는, 유저가 필터링 하지 않게 해 주세요.비동기/대기 또는 Promise를 사용하여 이를 보다 효과적으로 제어할 수 있어야 합니다.

예를 들어 다음과 같은 데이터 속성입니다.

isFiltering: false

당신이 했던 것과 같은 약속을 사용한다(여기에서는 코드를 생략하지만 다른 방법에서도 마찬가지이다).

methods: {
  getCustomers: async function () {
      var $this = this;
      this.isFiltering = true;
      return axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/customers?date=${$this.dateFilter}`).then(function(response) {
          $this.customers = response.data;
          $this.isFiltering = false;
      });
  }
}

HTML 에서는isFiltering입력을 무효로 합니다(CSS 또는 임의의 방법으로 추가).그러면 사용자가 필터링을 변경할 수 없고 필터링이 실행되는 것처럼 보입니다.반드시 추가해 주세요..catch설정 부분isFiltering잘못되면 거짓으로 만들죠사용..finally가능하다면 더 좋을 것이다

if isFiltering then disable

또 다른 방법은 Lodash의 Throttle 또는 기타 솔루션을 사용하거나 여기 S.O.에서 제안하는 이 구현: js의 단순 스로틀을 사용하는 것입니다.

이 스로틀 옵션은 사용자가 입력을 입력할 때처럼 연속되는 콜을 피하기 위해 적합합니다.

<template>
  <input type="date" :disabled="isDisabled" v-model="dateFilter">
</template>

<script>
export default {
  data () {
    return {
      dateFilter: null,
      modulesLoaded: 0,
      isDisabled: false
    }
  },
  watch: {
    dateFilter () {
      this.initStatModules()
    }
  },
  methods: {
    getCustomers () {
      axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/customers?date=${$this.dateFilter}`)
        .then(response => {
          this.customers = response.data
          this.onModuleLoaded()
        })
    },
    getBookings () {
      axios.get(`/api/v1/reports/${$this.team.id}/stats-dashboard/bookings`)
        .then(response => {
          this.bookings = response.data
          this.onModuleLoaded()
        })
    },
    getTotalRevenue () {
      axios.get(`/api/v1/reports/${$this.team.id}/services-revenue?date=${$this.dateFilter}`)
        .then(response => {
          this.totalRevenue = response.data.data.totalRevenue
          this.onModuleLoaded()
        })
    },
    initStatModules () {
      this.isDisabled = true
      this.modulesLoaded = 0
      this.getCustomers()
      this.getBookings()
      this.getTotalRevenue()
    },
    onModuleLoaded () {
      this.modulesLoaded++
      if (this.modulesLoaded === 3) {
        this.isDisabled = false
      }
    }
  }
}
</script>

이거 먹어봐.

언급URL : https://stackoverflow.com/questions/46492000/cancelling-multiple-api-calls-in-vue-js-with-axios

반응형