鴻蒙學習筆記二十一:網(wǎng)絡(luò)框架

最近對鴻蒙項目中的網(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 + "接口的公共部分"; //配置接口的公共部分
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者麸锉。
  • 序言:七十年代末钠绍,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子花沉,更是在濱河造成了極大的恐慌柳爽,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碱屁,死亡現(xiàn)場離奇詭異泻拦,居然都是意外死亡,警方通過查閱死者的電腦和手機忽媒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評論 3 399
  • 文/潘曉璐 我一進店門争拐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人晦雨,你說我怎么就攤上這事架曹。” “怎么了闹瞧?”我有些...
    開封第一講書人閱讀 168,814評論 0 361
  • 文/不壞的土叔 我叫張陵绑雄,是天一觀的道長。 經(jīng)常有香客問我奥邮,道長万牺,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評論 1 299
  • 正文 為了忘掉前任洽腺,我火速辦了婚禮脚粟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蘸朋。我一直安慰自己核无,他們只是感情好,可當我...
    茶點故事閱讀 68,888評論 6 398
  • 文/花漫 我一把揭開白布藕坯。 她就那樣靜靜地躺著团南,像睡著了一般噪沙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上吐根,一...
    開封第一講書人閱讀 52,475評論 1 312
  • 那天正歼,我揣著相機與錄音,去河邊找鬼拷橘。 笑死朋腋,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的膜楷。 我是一名探鬼主播旭咽,決...
    沈念sama閱讀 41,010評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼赌厅!你這毒婦竟也來了穷绵?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評論 0 277
  • 序言:老撾萬榮一對情侶失蹤特愿,失蹤者是張志新(化名)和其女友劉穎仲墨,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體揍障,經(jīng)...
    沈念sama閱讀 46,469評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡目养,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,552評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了毒嫡。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片癌蚁。...
    茶點故事閱讀 40,680評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖兜畸,靈堂內(nèi)的尸體忽然破棺而出努释,到底是詐尸還是另有隱情,我是刑警寧澤咬摇,帶...
    沈念sama閱讀 36,362評論 5 351
  • 正文 年R本政府宣布伐蒂,位于F島的核電站,受9級特大地震影響肛鹏,放射性物質(zhì)發(fā)生泄漏逸邦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,037評論 3 335
  • 文/蒙蒙 一在扰、第九天 我趴在偏房一處隱蔽的房頂上張望缕减。 院中可真熱鬧,春花似錦健田、人聲如沸烛卧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽总放。三九已至,卻和暖如春好爬,著一層夾襖步出監(jiān)牢的瞬間局雄,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評論 1 274
  • 我被黑心中介騙來泰國打工存炮, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留炬搭,地道東北人。 一個月前我還...
    沈念sama閱讀 49,099評論 3 378
  • 正文 我出身青樓穆桂,卻偏偏與公主長得像宫盔,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子享完,可洞房花燭夜當晚...
    茶點故事閱讀 45,691評論 2 361

推薦閱讀更多精彩內(nèi)容