最近對鴻蒙項目中的網(wǎng)絡(luò)框架進行了整理硬霍,拆分出一個單獨的網(wǎng)絡(luò)模塊
具體用法如下:
1:在業(yè)務(wù)模塊中添加對網(wǎng)絡(luò)模塊的依賴
找到業(yè)務(wù)模塊中的oh-package.json5文件,在dependencies中添加,示例如下:
{
"name": "usercenter",
"version": "1.0.0",
"description": "Please describe the basic information.",
"main": "Index.ets",
"author": "",
"license": "Apache-2.0",
"dependencies": {
"netWork": "file:../../Common/netWork"
}
}
2:添加上之后,點擊 Sync Now按鈕伊磺,同步代碼,代碼同步完成后即可引用網(wǎng)絡(luò)庫
image.png
3:使用示例
在網(wǎng)絡(luò)庫中我寫了一個示例頁面:NetTestPage和TestViewModel浊仆,用于展示具體的網(wǎng)絡(luò)請求調(diào)用方法,需要注意的是如果需要監(jiān)控當前接口請求的狀態(tài)酣溃,則需要使用this.httpRequest().promise()來包裹接口調(diào)用的方法——對應(yīng)為TestViewModel中的getSearchResult(),如果無需監(jiān)控則直接調(diào)用網(wǎng)絡(luò)請求即可——對應(yīng)為TestViewModel中的getSearchResultViewModel()
import { ViewStateConstant } from '../constant/ViewStateConstant'
import { TestViewModel } from '../businessViewModel/TestViewModel'
import { CommonDataSource } from '../viewmodels/CommonDataSource'
@Component
export struct NetTestPage {
@State commonDataSource: CommonDataSource<string> = new CommonDataSource([])
@State viewState: string = ViewStateConstant.VIEW_STATE_LOADING //展示骨架屏
private testViewModel: TestViewModel = new TestViewModel(this.commonDataSource)
aboutToAppear() {
this.testViewModel.observeState((state) => {
this.viewState = state
})
this.testViewModel.getSearchResult("測試", 1, () => {
//接口調(diào)用結(jié)束
})
}
build() {
RelativeContainer() {
this.normalContent()
if (this.viewState == ViewStateConstant.VIEW_STATE_LOADING) {
this.loadingContent()
}
}
.width('100%')
.height('100%')
}
//接口成功后的UI
@Builder
private normalContent() {
}
//接口加載中的UI纪隙,可以展示加載框或者骨架屏
@Builder
private loadingContent() {
}
}
import { ApiService } from '../../../../Index'
import { BaseViewModel } from '../viewmodels/BaseViewModel'
import { CommonDataSource } from '../viewmodels/CommonDataSource';
import { SearchResultData } from './SearchResultData'
export class TestViewModel extends BaseViewModel {
//注意:這里有g(shù)etSearchResult()和getSearchResultViewModel()兩個方法
//區(qū)別點在于getSearchResult()可以同步獲取當前網(wǎng)絡(luò)請求的狀態(tài)赊豌,比如加載中
//getSearchResultViewModel()不會同步網(wǎng)絡(luò)請求的狀態(tài)
testList: CommonDataSource<string>
constructor(testList: CommonDataSource<string>) {
super();
this.testList = testList
}
async getSearchResult(searchText: string, currPage: number, onFinish: () => void) {
await this.httpRequest().promise(this.getSearchResultViewModel1(searchText, currPage, onFinish))
}
//注意:這里的ApiService需要導入index中的,因為真實業(yè)務(wù)中網(wǎng)絡(luò)框架肯定不會和業(yè)務(wù)放在同一模塊中的
//示例:獲取搜索結(jié)果列表
getSearchResultViewModel1(searchText: string, currPage: number, onFinish: () => void) {
return ApiService.get<SearchResultData>({
url: 'www.baidu.com', //接口地址——不包含Host的公共部分绵咱,公共部分在GlobalConfig中配置
params: {
searchContent: `${searchText}`, //搜索時用到
page: currPage,
}
})
.then((result: SearchResultData) => {
//獲取數(shù)據(jù)成功
if (result.list) {
this.testList.addDatas(0,result.list)
}
})
.finally(() => {
//接口調(diào)用結(jié)束
onFinish()
})
}
//get請求:參數(shù)以path的形式放到接口地址中
getSearchResultViewModel2(searchText: string): Promise<string> {
return ApiService.get<string>({
url: `www.baodu.com/{searchText}/list`.replace('{searchText}',
searchText),
params: {
userType: searchText
}
})
}
//post請求:使用表單傳參
postSearchResultViewModel1(currPage: string, onFinish: () => void) {
return ApiService.post<Array<string>>({
url: 'www.baidu.com', //接口地址——不包含Host的公共部分碘饼,公共部分在GlobalConfig中配置
data: {
currPage: `${currPage}`
}
})
.then((result: Array<string>) => {
})
.finally(() => {
onFinish()
})
}
//post請求,不使用表單傳參
postSearchResultViewModel2(currPage: string): Promise<boolean> {
return ApiService.post<boolean>({
url: 'www.baidu.com', //接口地址——不包含Host的公共部分悲伶,公共部分在GlobalConfig中配置
isFormUrlEncoded: false, //不使用表單傳參
data: {
currPage: `${currPage}`
}
})
.then((result: boolean) => {
return result
})
}
}
4:在GlobalConfig中配置接口基地址
export class GlobalConfig {
static readonly APP_NAME = "APP的名稱" //刷新token時用到艾恼,如果無需刷新token則可刪除
static readonly HTTPS = "https://"
static SCHEMA = GlobalConfig.HTTPS
static HOST = GlobalConfig.SCHEMA + "接口的公共部分"; //配置接口的公共部分
}