使用方式:
打開Harmony第三方工具倉(cāng),找到axios,如圖:
第三方工具倉(cāng)網(wǎng)址:https://ohpm.openharmony.cn/#/cn/home
在你的項(xiàng)目執(zhí)行命令:ohpm install @ohos/axios
前提是你已經(jīng)裝好了ohpm ,如果沒有安裝,可以在官網(wǎng)找到詳細(xì)的安裝教程;
注意:不是在你的entry目錄下,比如你的項(xiàng)目名稱:
在父級(jí)目錄安裝。
接著封裝工具類,新建一個(gè)ts類:
import axios, { AxiosError, AxiosInstance, AxiosResponse, FormData, InternalAxiosRequestConfig } from '@ohos/axios'
import defaultAppManager from '@ohos.bundle.defaultAppManager';
import ResultData from './ResultData';
class AxiosUtil {
private instance: AxiosInstance;
constructor() {
this.instance = this.getInstance();
this.addInterceptor(this.instance)
}
getInstance(): AxiosInstance {
const instance = axios.create({
baseURL: "http://127.0.0.1:10001/jianshen"
})
return instance;
}
addInterceptor(instance: AxiosInstance): void {
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
if (config.url.concat('login')) {
// 如果是登錄路徑跳過,其余都需要帶上token
return config;
} else {
// 從全局緩存中取token
config.headers.set("Authorization", AppStorage.Get("token"))
return config;
}
}, (error: AxiosError) => {
return Promise.reject(error);
})
instance.interceptors.response.use((response: AxiosResponse) => {
if (response.status == 200) {
return response.data;
} else {
return Promise.reject(response.statusText)
}
}, (error: AxiosError) => {
return Promise.reject(error)
})
}
httpGet(url: string, params: object = {}) {
return new Promise((resolve, reject) => {
this.instance.get(url, params)
.then(response => {
resolve(response);
})
.catch(error => {
reject(error)
})
})
}
httpPost(url: string, params: object = {}) {
return new Promise((resolve, reject) => {
this.instance.post(url, params)
.then(response => {
resolve(response);
})
.catch(error => {
reject(error)
})
})
}
httpFileUpload(url: string, formData: FormData) {
return new Promise((resolve, reject) => {
this.instance.post(url, formData,
{
headers: { 'Content-Type': 'multipart/form-data' }
})
.then(response => {
resolve(response);
})
.catch(error => {
reject(error)
})
})
}
}
const axiosUtil: AxiosUtil = new AxiosUtil();
export default axiosUtil;
如何使用?
import axiosUtil from '../../common/AxiosUtil
然后就可以直接在你的arkts代碼中使用了;例如:文章來源:http://www.zghlxwxcb.cn/news/detail-854533.html
// @ts-nocheck
import CommonUtil from '../../common/CommonUtil'
import ResultData from '../../common/ResultData'
import axiosUtil from '../../common/AxiosUtil'
import { Banner } from './model/Banner'
import { Teacher } from './model/Teacher'
@Component
@Preview
export default struct ShowYePage {
@State message: string = '首頁(yè)'
private swiperController: SwiperController = new SwiperController();
@State bannerList: Banner[] = [];
@State teacherFilterValue: string = ''
@State teacherList: Teacher[] = [];
pageIndex: number = 1;
pageSize: number = 10;
total: number = 0;
arr:number[] = [1,2,3,4,5,6,7,8,9,10]
build() {
Scroll() {
Column() {
Flex({ justifyContent: FlexAlign.Center }) {
// 上面的搜索欄
Search({ placeholder: '支持按教練名稱/標(biāo)簽進(jìn)行查詢哦~' }).searchButton("搜索").onSubmit(value => {
this.teacherFilterValue = value;
})
}
.margin({ top: 14 })
// 輪播圖
Swiper(this.swiperController) {
if (this.bannerList.length > 0) {
ForEach(this.bannerList, item => {
Image(item.img).height(50).width('100%')
})
} else {
Text('占位')
}
}
.cachedCount(2) // 設(shè)置預(yù)加載子組件個(gè)數(shù)
.index(1) // 設(shè)置當(dāng)前在容器中顯示的子組件的索引值
.autoPlay(true) // 子組件是否自動(dòng)播放
.interval(4000) // 使用自動(dòng)播放時(shí)播放的時(shí)間間隔,單位為毫秒
.indicator(true) // 是否啟用導(dǎo)航點(diǎn)指示器
.loop(true) // 是否開啟循環(huán)
.duration(1000) // 子組件切換的動(dòng)畫時(shí)長(zhǎng),單位為毫秒
.itemSpace(0) // 設(shè)置子組件與子組件之間間隙
.curve(Curve.Linear) // 設(shè)置Swiper的動(dòng)畫曲線,默認(rèn)為淡入淡出曲線
.borderRadius(15)
.margin({top:14})
.height(150)
.onChange((index: number) => {
console.info(index.toString())
})
// 教練列表
Column() {
Flex({justifyContent:FlexAlign.Start}){
Text('教練列表').fontSize(24).fontWeight(500).padding({left:14})
}.height(50).width('100%')
List() {
ForEach(this.teacherList,(item:Teacher)=>{
ListItem() {
TeacherComponent({teacher:item})
}
})
}
.onReachEnd(()=>{
console.log('觸底了')
})
.onReachStart(()=>{
console.log('上拉了')
})
.width('100%')
.layoutWeight(1)
}
.borderRadius({ topLeft: 20, topRight: 20 })
.margin({ top: 20 })
.layoutWeight(1)
}.height('100%').width('100%')
}.height('100%').width('100%')
.padding({ left: 14, right: 14 })
}
aboutToAppear() {
this.getBannerList();
this.getTeacherList();
}
// 支持async和await的用法
async getBannerList() {
const result: Banner[] = await axiosUtil.httpPost("banner/list");
this.bannerList = result;
}
async getTeacherList() {
const params = {
pageIndex: this.pageIndex,
pageSize: this.pageSize,
filterValue: this.teacherFilterValue
}
const result = await axiosUtil.httpPost("teacher/list", params);
const teacherList = result.list;
this.teacherList = teacherList;
this.total = result.total;
}
}
@Component
struct TeacherComponent {
@State teacher:Teacher = null;
build() {
Flex({ justifyContent: FlexAlign.Center }) {
// 左側(cè)頭像
Flex({ justifyContent: FlexAlign.Start }) {
Image(this.teacher.avatar).width('100%').height('100%').borderRadius(10)
}.margin({ top: 5, bottom: 5, right: 5 }).height('95%').width('30%')
// 右側(cè)描述
Flex({justifyContent:FlexAlign.Start,direction:FlexDirection.Column}) {
Text(`教練名稱:${this.teacher.username}`).fontSize(24).fontWeight(100).fontStyle(FontStyle.Italic)
Text(`教練簡(jiǎn)介:${this.teacher.content}`).fontSize(18).fontWeight(90)
Text(`標(biāo)簽:${this.teacher.flag}`).fontSize(14)
}.margin({top:5,bottom:5,right:5}).height('100%').width('70%').onClick(()=>{
// 跳轉(zhuǎn)教練詳情頁(yè)面 帶參數(shù)id
console.log(this.teacher.id)
})
}
.height(150)
.width('100%')
.borderRadius(20)
.margin({bottom:20})
.backgroundColor(Color.White)
}
}
到此結(jié)束,有任何問題歡迎大佬留言指正文章來源地址http://www.zghlxwxcb.cn/news/detail-854533.html
到了這里,關(guān)于鴻蒙API9+axios封裝一個(gè)通用工具類的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!