日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

如何在typescript中使用axios来封装一个HttpClient类

發(fā)布時(shí)間:2023/12/2 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何在typescript中使用axios来封装一个HttpClient类 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

我們通常開(kāi)始直接在代碼中使用像axios這樣的第三方庫(kù)。這沒(méi)有錯(cuò)。但是,在不斷變化的庫(kù),軟件包,版本等世界中,直接使用這些庫(kù)API可能會(huì)導(dǎo)致代碼不一致。

一個(gè)好的做法是創(chuàng)建自己的抽象并將對(duì)庫(kù)API的調(diào)用包裝到包裝器中。這將使您保持代碼更加一致,并且在將來(lái)需要時(shí)也可以更輕松地切換到其他庫(kù)或者程序包。這是因?yàn)槟鷮⑺袑?duì)第三方庫(kù)的調(diào)用都包裝在一個(gè)位置,并且只要包裝器接口沒(méi)有更改,就可以替換包裝器方法的實(shí)現(xiàn)以切換到新庫(kù)。

讓我們開(kāi)始寫(xiě)代碼

在用于發(fā)出Http請(qǐng)求的代碼的特定情況下,我們可以創(chuàng)建一個(gè)名為IHttpClient的接口,然后創(chuàng)建一個(gè)名為HttpClient的類(lèi)來(lái)實(shí)現(xiàn)該接口。在我們的HttpClient方法中,我們將調(diào)用axios方法。

現(xiàn)在,讓我們假設(shè)HttpClient僅具有通用的get和post方法:

export interface IHttpClient {get<T>(parameters: IHttpClientRequestParameters): Promise<T>post<T>(parameters: IHttpClientRequestParameters): Promise<T> }

我們還需要一個(gè)接口,以將我們的參數(shù)傳遞給帶有一個(gè)參數(shù)的get和post,以避免代碼混亂。我們將其稱(chēng)為IHttpClientRequestParameters,它將花費(fèi)一些通用時(shí)間T來(lái)定義傳入的有效負(fù)載的類(lèi)型(如果有)以及用于任何類(lèi)型的Http請(qǐng)求的其他通用參數(shù):

export interface IHttpClientRequestParameters<T> {url: stringrequiresToken: booleanpayload?: T }

這是請(qǐng)求參數(shù)接口的每個(gè)屬性的詳細(xì)說(shuō)明:

url:這是我們需要向其發(fā)出請(qǐng)求的API端點(diǎn)的完整url(必須包含查詢字符串參數(shù))

requireToken:這是一個(gè)布爾值,指示我們的請(qǐng)求是否還必須添加身份驗(yàn)證令牌(即Jwt令牌)

有效負(fù)載:這是POST或PUT請(qǐng)求的有效負(fù)載,因此是可選的。現(xiàn)在,我們可以編碼HttpClient類(lèi),以實(shí)現(xiàn)IHttpClient接口并使用axios。首先,從axios導(dǎo)入所需的內(nèi)容,并編寫(xiě)尚未實(shí)現(xiàn)的HttpClient類(lèi)的初始聲明:

import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'export class HttpClient implements IHttpClient {// ... implementation code will go here }

現(xiàn)在,按照界面中的定義添加get方法的實(shí)現(xiàn)。請(qǐng)注意,這里我使用的是Promise語(yǔ)法,但是歡迎您使用async / await語(yǔ)法。我們的get方法將使用IHttpClientRequestParameters的實(shí)例并返回Promise:

get<T>(parameters: IHttpClientRequestParameters): Promise<T> {return new Promise<T>((resolve, reject) => {// extract the individual parametersconst { url, requiresToken } = parameters // axios request options like headers etcconst options: AxiosRequestConfig = {headers: {}}// if API endpoint requires a token, we'll need to add a way to add this.if (requiresToken) {const token = this.getToken()options.headers.RequestVerificationToken = token}// finally execute the GET request with axios:axios.get(url, options).then((response: any) => {resolve(response.data as T)}).catch((response: any) => {reject(response)})}) }

同樣,現(xiàn)在添加接口中定義的post方法的實(shí)現(xiàn)。像get一樣,我們的post方法將采用IHttpClientRequestParameters的實(shí)例并返回Promise:

post<T>(parameters: IHttpClientRequestParameters): Promise<T> {return new Promise<T>((resolve, reject) => {const { url, payload, requiresToken } = parameters// axios request options like headers etcconst options: AxiosRequestConfig = {headers: {}}// if API endpoint requires a token, we'll need to add a way to add this.if (requiresToken) {const token = this.getToken()options.headers.RequestVerificationToken = token}// finally execute the GET request with axios:axios.post(url, payload, options).then((response: any) => {resolve(response.data as T)}).catch((response: any) => {reject(response)})}) }

現(xiàn)在,您可以導(dǎo)出HttpClient的實(shí)例并在整個(gè)代碼中使用:

export const httpClient = new HttpClient()

這是一個(gè)示例,我們使用它來(lái)獲取IItem類(lèi)型的“項(xiàng)目”列表:

fetchItems(): Promise<IItem[]> {// prepare our request parametersconst getParameters: IHttpClientPostParameters = {url: 'http://yourapiurl/items',requiresToken: false}// just return httpClient.get (which is a promise) or again use async/await if you preferreturn httpClient.get<IItem[]>(getParameters) }

總結(jié)

現(xiàn)在,您有了一個(gè)HttpClient,它抽象了不同的Http請(qǐng)求(如get或post等)并將代碼封裝在一個(gè)地方。在HttpClient中,您可以使用axios或者其他平臺(tái)的請(qǐng)求庫(kù)亦或其他請(qǐng)求協(xié)議,這樣并不會(huì)污染你外部的代碼。

總結(jié)

以上是生活随笔為你收集整理的如何在typescript中使用axios来封装一个HttpClient类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。