user5062472
user5062472

Reputation:

VueJs Axios and Typescript

I was handed a base to develop a project on. It's made in Vue and Typescript, which doesn't have much support online.

I currently need to make several API calls in order to check the availability of a service, and must do those inside a component. For some reason, I'm not able to figure how to do so.

What I currently have is:

import * as Vue from 'vue';
import { Component } from 'vue-property-decorator';
import Axios, { AxiosInstance, AxiosRequestConfig, AxiosError, AxiosResponse, AxiosStatic } from 'axios';

@Component({
(...)  
})

export class Something extends Vue {
    public $http: Axios;
constructor() {
    super();
    this.$http = Axios.create({
        baseURL: "https://swapi.co/api/people/1/"
    });
}

testFunc() {
    let data: any;
    this.$http.get("https://swapi.co/api/people/1/", data)
       .then((res: AxiosResponse) => {
        console.log(res.data);
     })
      .catch((ex: any) => {
        console.log(ex);
      });
 }


}

There's several things that I've changed in order to get this to work, thus the code I've pasted counts more as a structure than anything else. I also have a button in my view that calls that testFunc(). Also, Axios doesn't get recognized as a type, and even if I import "axios" instead, it doesn't work. AxiosInstasnce does work, but gets me nowhere.

Upvotes: 6

Views: 4660

Answers (1)

Andreas Bauer
Andreas Bauer

Reputation: 121

I'm encapsulate HTTP/REST operations in separate .ts files and which I then call form a component or from the Vuex store. Here I also use async/await to have better readable code. Each method declared its input and return types.

import axios from 'axios'

const http = axios.create({
  baseURL: `${SOME_SERVICE_URL}/base-path`,
  headers: { 'Content-Type': 'application/json' }
})

export async function getItemById (itemId: string): Promise<Item> {
  const response = await http.get(`/${itemId}`)
  return response.data
}

export async function createItem (item: Item): Promise<Item> {
  const response = await http.post('/', JSON.stringify(item))
  return response.data
}

Upvotes: 1

Related Questions