rest.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios' export class Api { private api: AxiosInstance public constructor (config: AxiosRequestConfig) { this.api = axios.create(config) // this middleware is been called right before the http request is made. this.api.interceptors.request.use((param: AxiosRequestConfig) => ({ ...param })) // this middleware is been called right before the response is get it by the method that triggers the request this.api.interceptors.response.use((param: AxiosResponse) => ({ ...param })) /** 可以在这里定义一些header this.api.defaults.headers.common['x-api-key'] = KEY */ } public getUri (config?: AxiosRequestConfig): string { return this.api.getUri(config) } public request<T, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R> { return this.api.request(config); } //url需要自己定义 public get<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> { return this.api.get(url, config); } public delete<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> { return this.api.delete(url, config); } public head<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> { return this.api.head(url, config); } public post<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> { return this.api.post(url, data, config); } public put<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> { return this.api.put(url, data, config); } public patch<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> { return this.api.patch(url, data, config); } } |
使用这个API
1 2 3 4 5 6 7 8 9 10 11 12 | export class UserApi extends Api { constructor (config: AxiosRequestConfig) { // NEVER FORGET THE SUPER super(config); } async addUser(user: User): Promise<User|null> { const resource = '/user' const result = await this.post<User[]>(resource, user) return (result && result.data && result.data.length > 0) ? result.data[0] : null } } |