当前位置:   article > 正文

TypeScript封装axios——基本封装与拦截器精细控制_typescript 构造函数封装

typescript 构造函数封装

1、基本封装

封装一个Request的类,使得在外部可以调用此类的构造函数创建实例,创建的实例就对应axios实例,request/index.ts中代码如下:

import axios, {
    AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";

class HDRequest {
   
  // 创建这个类的目的:每个创建出的HDRequest的实例都对应一个axios实例

  // 创建实例的方法:constructor()构造实例
  instance: AxiosInstance;
  constructor(config: AxiosRequestConfig) {
   
    this.instance = axios.create(config);
  }

  // 二次封装网络请求的方法
  request(config: AxiosRequestConfig) {
   
    return this.instance.request(config);
  }
}

export default HDRequest;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

基本配置信息单独写在一个文件中,config/index.ts中代码如下:

export const BASE_URL = "http://codercba.com:8000";
export const TIME_OUT = 5000;
  • 1
  • 2

在service/index.ts中创建一个Request类的一个实例,并配置这个实例:

import HDRequest from "./request";
import {
    BASE_URL, TIME_OUT } from "./config/index";

const hdRequest = new HDRequest({
   
  baseURL: BASE_URL,
  timeout: TIME_OUT,
});

export default hdRequest;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在moduleds/home.ts中使用这个实例进行request:

import hdRequest from "..";

hdRequest
  .request({
   
    url: "/home/multidata",
  })
  .then((res) => {
   
    console.log(res.data);
  });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2、配置全局拦截器

request/index.ts

import axios, {
    AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";

class HDRequest {
   
  // 创建这个类的目的:每个创建出的HDRequest的实例都对应一个axios实例

  // 创建实例的方法:constructor()构造实例
  instance: AxiosInstance;
  constructor(config: HDRequestConfig) {
   
    this.instance = axios.create(config);

    // 添加全局拦截器,每个实例都有
    this.instance.interceptors.request.use(
      (config) => {
   
        console.log("全局请求成功的拦截");
        return config;
      },
      (err) => {
   
        console.log(
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号