Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

网络请求 - 分页加载 #53

Open
cnwutianhao opened this issue Jul 21, 2024 · 0 comments
Open

网络请求 - 分页加载 #53

cnwutianhao opened this issue Jul 21, 2024 · 0 comments

Comments

@cnwutianhao
Copy link
Owner

分页加载关键字: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
        }
      })
  }
}

六、效果演示

Kapture 2024-07-21 at 11 45 59

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant