6

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.

3
  • 1
    any update on the issue. Commented Jun 4, 2018 at 20:54
  • This was half a year ago. I'm not working at the same company, but I can check later on what I have done in order to fix it. Are you having the same issue? Commented Jun 5, 2018 at 10:35
  • I made it actually. But it is better to write your solution. Commented Jun 5, 2018 at 13:56

1 Answer 1

1

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
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.