TypeScript学习笔记之axios简单封装

TypeScript对比JavaScript最大的区别就是TypeScript是强类型的。这种强类型相比弱类型,可以在编译期间发现并纠正错误,降低了试错的成本(智能提示)也提升了代码的规范性。

axios封装

//http.ts

import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios'

const config = {
    baseURL: /*读取配置文件*/process.env.VUE_APP_BASE_API_URL,
    timeout: 10 * 1000,
    withCredentials: true
};

const requestInterceptor = (config: AxiosRequestConfig): AxiosRequestConfig => {
    //请求拦截器,自定义
    return config;
};

const http: AxiosInstance = axios.create(config);
http.interceptors.request.use(requestInterceptor, error => Promise.reject(error))
http.interceptors.response.use(response => Promise.resolve(response), error => Promise.reject(error))

export function httpRequest<T>(config: AxiosRequestConfig): Promise<T> {
    const promise = http.request<T, AxiosResponse<T>>(config);
    return convertAxiosResponse(promise);
}

export function httpGet<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.get<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpDelete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.delete<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpHead<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.head<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpOptions<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.options<T, AxiosResponse<T>>(url, config);
    return convertAxiosResponse(promise);
}

export function httpPost<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.post<T, AxiosResponse<T>, D>(url, data, config)
    return convertAxiosResponse(promise);
}

export function httpPut<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.put<T, AxiosResponse<T>, D>(url, data, config);
    return convertAxiosResponse(promise);
}

export function httpPatch<T, D>(url: string, data?: D, config?: AxiosRequestConfig): Promise<T> {
    const promise = http.patch<T, AxiosResponse<T>, D>(url, data, config);
    return convertAxiosResponse(promise);
}

/**
 * @param axiosPromise AxiosResponse<T>
 */
function convertAxiosResponse<T>(axiosPromise: Promise<AxiosResponse<T>>): Promise<T> {
    return new Promise(function (resolve, reject) {
        axiosPromise.then(response => {
            resolve(response.data)
        }).then(err => {
            reject(err)
        });
    });
}

接口返回实体

因为是强类型的,支持泛型,所有我们可以把数据封装成一个实体类(或接口),这样参数就一目了然,类似Java中JavaBean的使用。
如果接口返回有统一的格式,如:

{
    "code": 200,
    "msg": "success",
    "data": any
}

那么就可以定义一个Base类(或接口),data以泛型参数传入。

//api-bean.ts

export interface ApiResponse<T = any> {
    code: number;
    msg: string;
    data: T;
}

export interface UserInfoBean {
    createdAt: string;
    id: number;
    userId: string;
    userType: string;
    username: string;
}

/**
 * 登录使用
 */
export interface UserLoginBean {
    userId: string;
    password: string;
    userType: string;
}

使用示例


import {httpGet, httpPost} from "@/util/http"
import {ApiResponse, UserInfoBean, UserLoginBean} from "@/bean/api-bean";

httpGet<ApiResponse<UserInfoBean[]>>("/srs_rtc/user/getAllUserInfo")
    .then((response) => {
      console.log("httpGet:", response)
    })
const login: UserLoginBean = {
  userId: "test",
  password: "1",
  userType: "0"
}
httpPost<ApiResponse<UserInfoBean>, UserLoginBean>("/srs_rtc/user/userLogin", login).then(response => {
  console.log("httpPost:", response)
}).then(error => {
  //
})

使用的时候就有智能提示了,相比JavaScript是不是爽很多?
示例

本人刚刚入手TypeScript,如有使用不当之处,欢迎指正。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冬季穿短裤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值