繁体   English   中英

Vue.js / Axios:如何从复杂的 Axios 结构中返回数据?

[英]Vue.js / Axios : How to return data from a complex Axios structure?

我正在使用 Vue.js + typescript + axios 开发一个项目,实际上我正在尝试创建一个复杂的 ApiRequest。 换句话说,我不想这样做:

data (){
    return {
        users:[]
    }
},

methods: {
    getUsers : function() {
        axios
          .get("http://localhost:9090/Users")
          .then(response => {
            this.users = response.data;
            console.log(response.data);
          })
          .catch(e => {
            console.log(e);
          });
    }
}

因为在一个大项目中是不够可维护的。

取而代之的是,我创建了一个“ApiService.ts”文件,我在其中声明了 GET 函数:

import axios from "axios";

import { ApiRequest } from "../models/api/ApiRequest";
import { HttpMethod } from "../enums/HttpMethod";

const httpClient = axios.create({
    baseURL: "http://localhost:9090"
});

class ApiService {

    async get<T=any>(url: string): Promise<T>{
        return await this.perform<T>({
            method: HttpMethod.GET,
            url,
        });
    }


    private async perform<T = any>(request: ApiRequest): Promise<T> {
        try {
            const response =  await httpClient({
                method: request.method,
                url: request.url,
            });
            console.log(response.data)
            return response.data
        }   catch (error) {
            const message = error.response
            ? error.response.data.message
            : error.message;
    
            throw Error (message);   
        }
    }
}

export const apiService = new ApiService();

我将它导入到我的文件 1 中:

data (){
    return {
        users:[]
    }
},

methods: {
    getUsers : function() {

    this.users = apiService.get("/Users");
    }
}

最后,我在同一个文件 1 中调用了函数和我的用户数组,如下所示:

<button @click= "getUsers"> Click here to get users </button>

<div> {{users}} </div>

但是:当我点击...发生了什么事

稍微解释一下,我的用户数组包含一个不稳定的“对象承诺”,但我的函数可以在控制台中工作,正如您在 console.log 中看到的那样,数组出现了。

所以,有人可以解释我如何才能在我的用户数组而不是“对象承诺”中显示我的不同用户? 这个“对象承诺”是什么?

非常感谢 !

get函数的返回类型是 Promise,因为该函数是async函数。 这就是为什么你得到 Promise 对象。 所以在调用apiService.get()函数时应该使用async/await

methods: {
    getUsers : async function() {
        this.users = await apiService.get("/Users");
    }
}

另外,如果你想向用户展示,你可以这样做:

<button @click= "getUsers"> Click here to get users </button>

<div
  v-for="(item, index) in users"
  :key="index"
>
  {{ `Name: ${item.name}, Address: ${item.address}` }}
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM