如何处理axios中的空响应?

时间:2017-08-28 17:21:10

标签: javascript vue.js axios

我使用axiosvue.js来获取数据作为无限制分页。当没有要呈现的数据时,它可以正常工作:

 fetchData() {
     this.loading = true
     this.page++;
     axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( 
     response => 
     //how to exist  if there is no data in the response?
      this.jokes = response.data).catch(function (error) {
        console.log(error);
      });

我想知道当我们到达最后一页并且没有更多数据要显示时如何停止渲染?

我看过docs,但找不到答案。

2 个答案:

答案 0 :(得分:2)

可能会介绍一些基本的标志逻辑。我已经采取了自由的假设,但你可以随时定义你的逻辑

fetchData() {
    this.loading = true;
    if (this.page > 0) {
        axios.get(this.BASE_URL + '/api/jokes/page=' + this.page)
            .then(response => {
                const isDataAvailable = response.data && response.data.length;
                this.jokes = isDataAvailable ? response.data : [];
                this.page = isDataAvailable ? (this.page + 1) : 0;
            })
            .catch(function(error) {
                console.error(error);
            });
    }
}

答案 1 :(得分:0)

您可以抛出一个自定义错误,该错误将被 catch 方法捕获。

 fetchData() {
 this.loading = true
 this.page++;
 axios.get(this.BASE_URL + '/api/jokes/'+'?page='+this.page).then( 
 response => {
   //how to exist  if there is no data in the response?
   if (!response.data || response.data.length == 0) {
     const emptyDataError = new Error('Invalid data');
     emptyDataError.statusCode = 500;
     throw emptyDataError;
   }
   this.jokes = response.data;
 }).catch(function (error) {
   console.log(error);
 });