【HarmonyOS NEXT】网络请求 - 分页加载
分页加载关键字:
onReachEnd
一、申请网络权限
在 module.json5
文件中,添加网络权限:
{
"module": {
...
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"usedScene": {
"when": "always"
}
}
]
}
}
二、创建数据结构体
export default class NewsInfo {
title: string = ''
thumbnail: string = ''
publish_time: string = ''
source: string = ''
origin: string = ''
}
import NewsInfo from '../viewmodel/NewsInfo'
export default class NewsData {
code: string = ''
data: NewsInfo[] = []
}
三、封装网络请求
import NewsData from '../viewmodel/NewsData';
import http from '@ohos.net.http';
class NewsModel {
baseURL: string = 'https://china.nba.cn/cms/v1'
pageNo: number = 1
getNewsList(): Promise<NewsData> {
return new Promise((resolve, reject) => {
let httpRequest = http.createHttp()
httpRequest.request(
`${this.baseURL}/news/list?column_id=57&page_size=5&page_no=${this.pageNo}&app_key=tiKB2tNdncnZFPOi&os_type=3&os_version=10.0&app_version=1.0.0&install_id=202111201544&network=wifi&t=1716876416465&device_id=6bdaac33a8df720345a767431e62caf3&channel=nba&sign=48da38cc43775e0efea30a3726328530`,
{
method: http.RequestMethod.GET
}
)
.then(response => {
if (response.responseCode === 200) {
console.log('查询新闻信息成功!', response.result)
resolve(JSON.parse(response.result.toString()))
} else {
console.log('查询新闻信息失败!error:', JSON.stringify(response))
reject('查询新闻信息失败')
}
})
.catch((error: Error) => {
console.log('查询新闻信息失败!error:', JSON.stringify(error))
reject('查询新闻信息失败')
})
})
}
}
const newsModel = new NewsModel()
export default newsModel as NewsModel
四、创建 item 布局
import NewsInfo from '../viewmodel/NewsInfo'
@Component
export default struct NewsItem {
news: NewsInfo = new NewsInfo()
build() {
Column({ space: 5 }) {
Column() {
Image(this.news.thumbnail)
Text(this.news.title)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.ellipsisMode(EllipsisMode.END)
}
.width('100%')
}
}
}
五、实现网络请求分页加载
import NewsInfo from '../viewmodel/NewsInfo'
import NewsItem from '../views/NewsItem'
import NewsModel from '../model/NewsModel'
@Entry
@Component
struct Index {
@State news: NewsInfo[] = []
isLoading: boolean = false
isMore: boolean = true
aboutToAppear(): void {
this.loadNewsInfo()
}
build() {
Column() {
List({ space: 10 }) {
ForEach(this.news, (news: NewsInfo) => {
ListItem() {
NewsItem({ news: news })
}
})
}
.width('100%')
.onReachEnd(() => {
console.log('触底了!')
if (!this.isLoading && this.isMore) {
this.isLoading = true
// 翻页
NewsModel.pageNo++
this.loadNewsInfo()
}
})
}
.width('100%')
.height('100%')
.padding(10)
}
loadNewsInfo() {
NewsModel.getNewsList()
.then(newsData => {
this.news = this.news.concat(newsData.data)
this.isLoading = false
if (!newsData.data || newsData.data.length == 0) {
this.isMore = false
}
})
}
}
六、效果演示
原文地址:https://blog.csdn.net/cnwutianhao/article/details/140585518
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!