HarmonyOS 鸿蒙Next中接口请求返回数据如何赋值,并通过list组件加载

HarmonyOS 鸿蒙Next中接口请求返回数据如何赋值,并通过list组件加载

10 回复

楼主参考一下这个demo的写法,已经实现了完整的数据请求和list加载:https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials_NEXT-NewsRelease

你2楼提供的代码参考该demo改一下就不会报错了:

httpRequest.request('http://wmapp.xiaoyunba.com/api/index/kefu', {}).then((resp) => {
  console.info("---124调用后台接口返回---", JSON.stringify(resp))
  let result = `${resp.result}`;
  let newsResult: tits = JSON.parse(result);
}).catch(() => {
  console.info("---接口错误信息---", "请求失败")
})

更多关于HarmonyOS 鸿蒙Next中接口请求返回数据如何赋值,并通过list组件加载的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


楼主这个问题会涉及到架构分层问题:鸿蒙里面常用的MVVM模式

网络请求获取数据和数据在List组件展示ViewModel层和View去处理

Model:数据访问层。以数据为中心,不直接与用户界面交互。负责数据结构定义,数据管理(获取、存储、更新等),以及业务逻辑处理。

View:用户界面层。负责用户界面展示并与用户交互,不包含任何业务逻辑。它通过绑定ViewModel层提供的数据实现动态更新。

ViewModel:表示逻辑层。作为连接Model和View的桥梁,通常一个View对应一个ViewModel。View和ViewModel有两种通信方式:

1.方法调用:View通过事件监听用户行为,在回调里面触发ViewModel层的方法。例如你想展示接口的数据,进入页面后在aboutToAppear里面请求数据,在页面的ViewModel中处理好数据

aboutToAppear(): void {
//请求数据
this.dataInfo=....
}

2.双向绑定:View绑定ViewModel的数据,获取到数据后在页面也就是View层渲染数据,例如:this.dataInfo是已经在aboutToAppear获取到的数据

List() {
  ForEach(this.dataInfo, (item: relationalStore.ValuesBucket, index: number) => {
    ListItem() {
      Row() {
        Text(item['id']?.toString())
        Divider()
          .vertical(true)
          .height(30)
        Text(item['name']?.toString())
        Divider()
          .vertical(true)
          .height(30)
        Text(item['age']?.toString())
        Divider()
          .vertical(true)
          .height(30)
        Text(item['salary']?.toString())
        Divider()
          .vertical(true)
          .height(30)
      }
    }
  })
}
.width('100%')
.layoutWeight(1)

使用@kit.NetworkKit的HTTP模块请求接口,处理响应数据

import http from '[@kit](/user/kit).NetworkKit';

@State dataList: Array<ItemModel> = []; // 定义状态数组
async fetchData() {
  let requestBody = JSON.stringify({ page: 1 }); // 请求参数序列化
  try {
    const response = await http.createHttp().request(
      'https://example.com/api/data',
      { method: http.RequestMethod.POST, header: { 'Content-Type': 'application/json' }, extraData: requestBody }
    );
    const result = JSON.parse(response.result); // 解析JSON数据
    this.dataList = result.list.map(item => new ItemModel(item)); // 转换为模型对象
  } catch (err) {
    console.error('请求失败:', err);
  }
}

结合ForEach循环渲染数据条目

@Component
struct DataListComponent {
  @State dataList: ItemModel[] = [];

  build() {
    List() {
      ForEach(this.dataList, (item: ItemModel, index) => {
        ListItem() {
          Text(item.title)
            .fontSize(16)
            .margin({ top: 12 })
        }
      }, (item) => item.id.toString())
    }
    .onAppear(() => this.fetchData()) // 组件显示时触发请求
  }
}

https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials_PageAndData03
这是codelabs视频课程,网络获取数据列表展示,可以跟着一步步qiao

使用@kit.NetworkKit中的http模块发送网络请求,解析JSON响应数据:

@State dataList: object[] = []

http.request(url, (err, res) => {
  if (!err) {
    this.dataList = JSON.parse(res.result).dataArray // 这里假如接口返回数组字段为dataArray
  }
})

创建Model类匹配接口数据结构:

class ContentItem {
  id: string
  title: string
  constructor(id: string, title: string) {
    this.id = id
    this.title = title
  }
}

通过List+ForEach实现动态渲染:

struct DataListView {
  @State dataList: ContentItem[] = []
  
  build() {
    List() {
      ForEach(this.dataList, (item: ContentItem) => {
        ListItem() {
          Text(item.title).fontSize(16)
        }
      }, (item) => item.id) // 生成器确保唯一性
    }
    .onAppear(() => {
      this.loadData() // 触发数据加载
    })
  }
  
  private loadData() {
    // 执行网络请求逻辑
  }
}
class Userinfo {
  id: number;
  title: string;
  number: string;
  constructor(id:number,title:string,number:string){
    this.id = id;
    this.title = title;
    this.number = number;
  }
}

class tits {
  code: number;
  msg: string;
  time: string;
  data: Array<Userinfo>;
  constructor(code:number,msg:string,time:string,data:Array<Userinfo>){
    this.code = code;
    this.msg = msg;
    this.time = time;
    this.data = data;
  }
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State nums:string = '1';
  @State num2:string = '20';
  @State dataList: Userinfo[] = [];
  scroller: Scroller = new Scroller();

  aboutToAppear(): void {
    let httpRequest = http.createHttp();
    httpRequest.request('http://wmapp.xiaoyunba.com/api/index/kefu',{

    }).then((resp) => {
      console.info("---124调用后台接口返回---", JSON.stringify(resp.result))
      let newsResult:tits = resp.result;
    }).catch(() => {
      console.info("---接口错误信息---", "请求失败")
    })
  }
}

刚开始学鸿蒙开发,赋值一直报错,哪块写的有问题吗?

楼主参考一下这个demo的写法:https://developer.huawei.com/consumer/cn/codelabsPortal/carddetails/tutorials_NEXT-NewsRelease

你那块的可以改成:

httpRequest.request('http://wmapp.xiaoyunba.com/api/index/kefu', {}).then((resp) => {
  console.info("---124调用后台接口返回---", JSON.stringify(resp))
  let result = `${resp.result}`;
  let newsResult: tits = JSON.parse(result);
}).catch(() => {
  console.info("---接口错误信息---", "请求失败")
})

这是提问帖还是记录帖

在HarmonyOS Next中,接口返回数据通过异步回调获取。使用HTTP模块发起请求,在on(‘dataReceive’)事件中解析响应数据。将解析后的数据赋值给@State@Link装饰的数组变量。List组件通过ForEach遍历该数组,动态渲染列表项。数据更新时,UI自动刷新。

在HarmonyOS Next中,通过接口请求获取数据并赋值给List组件,可以按照以下步骤实现:

  1. 使用HTTP模块发起请求:通过@ohos.net.http模块创建httpRequest对象,配置请求参数并发送。
  2. 解析响应数据:在请求成功的回调中,解析返回的JSON数据,并转换为List组件所需的数据结构(例如数组)。
  3. 数据绑定到状态变量:使用@State装饰器声明一个状态变量(如dataArray),将解析后的数据赋值给该变量。
  4. List组件加载数据:在UI中通过List组件遍历dataArray,使用ForEach渲染每一项内容。

示例代码片段:

import http from '@ohos.net.http';

@Entry
@Component
struct DataListPage {
  @State dataArray: Array<Object> = [];

  aboutToAppear() {
    let httpRequest = http.createHttp();
    httpRequest.request(
      "https://api.example.com/data",
      { method: http.RequestMethod.GET },
      (err, data) => {
        if (!err) {
          this.dataArray = JSON.parse(data.result as string);
        }
      }
    );
  }

  build() {
    List() {
      ForEach(this.dataArray, (item: Object) => {
        ListItem() {
          Text(item['title']).fontSize(16)
        }
      })
    }
  }
}

注意:实际使用时需处理错误状态、加载状态及列表项键值优化。

回到顶部