鸿蒙学习笔记二十一:网络框架

最近对鸿蒙项目中的网络框架进行了整理,拆分出一个单独的网络模块
具体用法如下:
1:在业务模块中添加对网络模块的依赖

找到业务模块中的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按钮,同步代码,代码同步完成后即可引用网络库
image.png
3:使用示例

在网络库中我写了一个示例页面:NetTestPage和TestViewModel,用于展示具体的网络请求调用方法,需要注意的是如果需要监控当前接口请求的状态,则需要使用this.httpRequest().promise()来包裹接口调用的方法——对应为TestViewModel中的getSearchResult(),如果无需监控则直接调用网络请求即可——对应为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, () => {
      //接口调用结束
    })
  }

  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 {
  //注意:这里有getSearchResult()和getSearchResultViewModel()两个方法
  //区别点在于getSearchResult()可以同步获取当前网络请求的状态,比如加载中
  //getSearchResultViewModel()不会同步网络请求的状态

  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中的,因为真实业务中网络框架肯定不会和业务放在同一模块中的
  //示例:获取搜索结果列表
  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) => {
        //获取数据成功
        if (result.list) {
          this.testList.addDatas(0,result.list)
        }
      })
      .finally(() => {
        //接口调用结束
        onFinish()
      })
  }

  //get请求:参数以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 + "接口的公共部分"; //配置接口的公共部分
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容