鸿蒙 ArkUI 请求网络接口解析json数组加载显示在list组件中

团队介绍

作者:徐庆

团队:坚果派 公众号:"大前端之旅" 润开鸿生态技术专家,华为HDE,CSDN博客专家,CSDN超级个体,CSDN特邀嘉宾,InfoQ签约作者,OpenHarmony布道师,电子发烧友专家博客,51CTO博客专家,擅长HarmonyOS/OpenHarmony应用开发、熟悉服务卡片开发。欢迎合作。

前言:

各位同学有段时间没有见面 因为一直很忙所以就没有去更新博客。最近有在学习这个鸿蒙的ark ui开发 因为鸿蒙不是发布了一个鸿蒙next的测试版本 明年会启动纯血鸿蒙应用 所以我就想提前给大家写一些博客文章 今天要讲的是请求网络数据并显示到listview

添加网络权限

json 复制代码
"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]

具体实现:

1 定义数据模型

ini 复制代码
export class MenuModel {
  ret: string = ""
  data: Array<ShiCi> = []
}

export class ShiCi {
  id: string = ""
  title: string = ""
  pic: string = ""
  collect_num: string = ""
  food_str: string = ""
  num: string = ""
}

2 加载网络数据

接口地址 www.qubaobei.com/ios/cf/dish... 请求参数

名称 必填 类型 描述 示例
stage_id true string 条件参数
limit true string 每一页显示多少条
page true string 页码

网络请求封装

typescript 复制代码
import http from '@ohos.net.http';
import Constants, { ContentType } from '../common/constant/Constants';
import Logger from './Logger';

export function httpRequestGet(url: string) {
  return httpRequest(url, http.RequestMethod.GET);
}
/*export function httpRequestGet(url: string, params?:string) {
  return httpRequest(url, http.RequestMethod.GET,params);
}*/

export function httpRequestPost(url: string, params?:string ) {
  return httpRequest(url, http.RequestMethod.POST, params);
}

function httpRequest(url: string, method: http.RequestMethod,params?: string){
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    readTimeout: Constants.HTTP_READ_TIMEOUT,//读取超时时间 可选,默认为60000ms
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Constants.HTTP_READ_TIMEOUT,//连接超时时间  可选,默认为60000ms
    extraData: params // 请求参数
  });
  return responseResult.then((value: http.HttpResponse)=>{
      Logger.error("请求状态 --> "+value.responseCode)
     if(value.responseCode===200){
       Logger.error("请求成功");
       let getresult = value.result;
       Logger.error('请求返回数据', JSON.stringify(getresult));
       return getresult;
     }
  }).catch((err)=>{
    httpRequest.off('headersReceive');
    // 当该请求使用完毕时,调用destroy方法主动销毁
    httpRequest.destroy();
    return "";
  });
}

日志工具类

kotlin 复制代码
import hilog from '@ohos.hilog';

class Logger {
  private domain: number;
  private prefix: string;
  private format: string = '%{public}s, %{public}s';

  /**
   * constructor.
   *
   * @param Prefix Identifies the log tag.
   * @param domain Domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF.
   */
  constructor(prefix: string = 'MyApp', domain: number = 0xFF00) {
    this.prefix = prefix;
    this.domain = domain;
  }

  debug(...args: string[]): void {
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]): void {
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]): void {
    hilog.warn(this.domain, this.prefix, this.format, args);
  }

  error(...args: string[]): void {
    hilog.error(this.domain, this.prefix, this.format, args);
  }
}

export default new Logger('HTTPS', 0xFF00)

在UI中调用工具类请求网络

  • 因为我们一进去就要请求网络 所以会我们要在 aboutToAppear 方法中进行
javascript 复制代码
async  aboutToAppear(){
   Logger.error(this.TAG+' aboutToAppear  --- > ');
  let networkurl=CommonConstant.MENU;
  await httpRequestGet(networkurl).then((data)=>{
          console.log("data --- > "+data);
          Logger.error("登录请求回调结果 ---> " +data.toString());
    let menuModel: MenuModel = JSON.parse(data.toString())
    this.JokeList = menuModel.data

  });
 }

解析json将我们的json数据转换成一个对象然后复制给我们的 menuModel 我们取到里面的 JokeList 赋值我们的成员变量的 JokeList

kotlin 复制代码
this.JokeList = menuModel.data

我们就可以在我们的build里面去使用数据加载到list各个UI组件中 (这里因为我们接口返回的图片的url访问不了我就找了一张其他图片 代替 这里写法差异不大 大家需要注意 )

然后在我们的build中显示加载数据到list组件里面去

scss 复制代码
build() {
  Row() {
    List({ space: commonConst.LIST_ITEM_SPACE }) {
      ForEach(this.JokeList, (item) => {
        ListItem() {
          Row() {
            Column() {
              Image('https://www.itying.com/images/flutter/2.png')
                .width(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
                .height(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
            }
            .width(commonConst.GOODS_IMAGE_WIDTH)
            .height(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
            Column() {
              Text(item?.title)
                .fontSize(commonConst.NORMAL_FONT_SIZE)
                .margin({ bottom: commonConst.BIGGER_FONT_SIZE })

              Text(item?.food_str)
                .fontColor($r('app.color.gray'))
                .fontSize(commonConst.GOODS_EVALUATE_FONT_SIZE)
                .margin({ right: commonConst.MARGIN_RIGHT, bottom: commonConst.BIGGER_FONT_SIZE })

              Text('喜欢人数:'+item?.num)
                .fontColor($r('app.color.gray'))
                .fontSize(commonConst.GOODS_EVALUATE_FONT_SIZE)
                .margin({ right: commonConst.MARGIN_RIGHT, bottom: commonConst.BIGGER_FONT_SIZE })
            }
            .padding(commonConst.GOODS_LIST_PADDING)
            .width(commonConst.GOODS_FONT_WIDTH)
            .height(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
          }
          .justifyContent(FlexAlign.SpaceBetween)
          .height(commonConst.GOODS_LIST_HEIGHT)
          .width(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
        }
      })
    }
    .width(commonConst.GOODS_LIST_WIDTH)
  }
  .justifyContent(FlexAlign.Center)
  .width(commonConst.LAYOUT_WIDTH_OR_HEIGHT)
}

最终效果图

最后总结:

整个网络请求和json解析和我们Android还有Flutter都非常像, 需要创建一个model类然后接收 ,请求的时机要是跟我们安卓和Flutter很像需要根据视图的生命周期方法来处理。比较好理解 那么今天的文章就讲到这里 有兴趣的同学可以对照文章进行学习和扩展。最后呢 希望我都文章能帮助到各位同学工作和学习 如果你觉得文章还不错麻烦给我三连 关注点赞和转发 谢谢

相关推荐
特立独行的猫a4 小时前
HarmonyOS NEXT 诗词元服务项目开发上架全流程实战(一、项目介绍及实现效果)
华为·harmonyos·元服务·上架
云和数据.ChenGuang7 小时前
鸿蒙版电影app设计开发
华为·harmonyos·鸿蒙·鸿蒙系统
Bruce_Liuxiaowei8 小时前
HarmonyOS Next~鸿蒙系统UI创新实践:原生精致理念下的设计革命
ui·华为·harmonyos
SuperHeroWu714 小时前
【HarmonyOS 5】鸿蒙检测系统完整性
华为·harmonyos·模拟器·系统完整性·越狱设备
京东云开发者14 小时前
Taro on Harmony :助力业务高效开发纯血鸿蒙应用
harmonyos
前端付豪15 小时前
2、ArkTS 是什么?鸿蒙最强开发语言语法全讲解(附实操案例)
前端·后端·harmonyos
zhujiaming15 小时前
鸿蒙端应用适配使用开源flutter值得注意的一些问题
前端·flutter·harmonyos
前端付豪15 小时前
8、鸿蒙动画开发实战:做一个会跳舞的按钮!(附动效示意图)
前端·后端·harmonyos
前端付豪15 小时前
3、构建你的第一个鸿蒙组件化 UI 页面:实现可复用的卡片组件(附实战代码)
前端·后端·harmonyos
前端付豪15 小时前
7、打造鸿蒙原生日历组件:自定义 UI + 数据交互(附实操案例与效果图)
前端·后端·harmonyos