132 lines
2.8 KiB
TypeScript
132 lines
2.8 KiB
TypeScript
import {Utils} from '../utils';
|
||
import axios, {AxiosInstance} from 'axios';
|
||
|
||
/**
|
||
* 小程序端不可用
|
||
*/
|
||
export class Axios {
|
||
private instance: AxiosInstance;
|
||
|
||
// @ts-ignore
|
||
public async constructor() {
|
||
this.instance = axios.create({
|
||
baseURL: Utils.CheckAjaxUrl(),
|
||
timeout: 3000
|
||
});
|
||
this.ResponseInterceptor();
|
||
this.RequestInterceptor();
|
||
}
|
||
|
||
/**
|
||
* Get 请求
|
||
* 请求参数请参考接口:RequestParams
|
||
* @param params
|
||
*/
|
||
public async get(params: { url: string, data: Object }): Promise<Object> {
|
||
// let token:string = localStorage.getItem('token') || ''
|
||
// if(!!token) token = JSON.parse(token);
|
||
try {
|
||
return await this.instance.get(params.url, {
|
||
params: params.data
|
||
})
|
||
} catch (e) {
|
||
return e.message
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Post 请求
|
||
* 请求参数请参考接口:RequestParams
|
||
* @param params
|
||
*/
|
||
public async post(params: { url: string, data: Object, headers?: Object }): Promise<Object> {
|
||
console.log(Utils.CheckAjaxUrl()+params.url);
|
||
try {
|
||
return await this.instance.post(params.url, params.data, {})
|
||
} catch (e) {
|
||
return e.message
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Put 请求
|
||
* 请求参数请参考接口:RequestParams
|
||
* @param params
|
||
*/
|
||
public async put(params: { url: string, data: Object }): Promise<Object> {
|
||
try {
|
||
return await this.instance.put(params.url, params.data)
|
||
} catch (e) {
|
||
return e.message
|
||
}
|
||
}
|
||
|
||
/**
|
||
* delete 请求
|
||
* 请求参数请参考接口:RequestParams
|
||
* @param params
|
||
*/
|
||
public async delete(params: { url: string, data: Object }): Promise<Object> {
|
||
try {
|
||
return await this.instance.delete(params.url, {params: params.data})
|
||
} catch (e) {
|
||
return e.message
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 添加响应拦截器
|
||
* @constructor
|
||
*/
|
||
public async ResponseInterceptor(): Promise<any> {
|
||
this.instance.interceptors.response.use(response => {
|
||
this.CloseLoadingData();
|
||
switch (response.data.status) {
|
||
case 1:
|
||
return response.data.data;
|
||
break;
|
||
case 500:
|
||
console.log(response.data.msg);
|
||
break;
|
||
default:
|
||
console.log(response.data.msg);
|
||
break;
|
||
}
|
||
}, function (error) {
|
||
return Promise.reject(error)
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 添加请求拦截器
|
||
* @constructor
|
||
*/
|
||
public async RequestInterceptor(): Promise<any> {
|
||
this.instance.interceptors.request.use(config => {
|
||
this.OpenLoadingData();
|
||
return config
|
||
}, function (error) {
|
||
return Promise.reject(error)
|
||
})
|
||
}
|
||
|
||
/**
|
||
* 显示加载进度
|
||
* @constructor
|
||
*/
|
||
private OpenLoadingData(): void {
|
||
uni.showLoading({
|
||
title: '加载中...',
|
||
mask: true
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 清除加载进度条
|
||
*/
|
||
private CloseLoadingData(): void {
|
||
uni.hideLoading();
|
||
}
|
||
|
||
}
|