I am currently working on a project that involves Vue.js, TypeScript, and Axios. My main focus is on creating a complex ApiRequest. Unlike the traditional method of fetching data using axios directly in the component, I wanted to find a more maintainable solution for a large-scale project.
Instead of the conventional approach, I decided to create an "ApiService.ts" file where I defined the GET function:
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();
I then imported it into my original file:
data (){
return {
users:[]
}
},
methods: {
getUsers : function() {
this.users = apiService.get("/Users");
}
}
Finally, I called the function to populate the users Array in the same file as follows:
<button @click= "getUsers"> Click here to get users </button>
<div> {{users}} </div>
However, when I click the button, I encountered an unexpected behavior which you can view here.
Essentially, my users Array contains a "Object Promise" instead of the actual user data. Can anyone provide insight on how to display the user data correctly in my users Array rather than just a promise object? Additionally, what exactly is this "object Promise"?
Thank you!