You need to enable JavaScript to run this app. 在Angular中如何使用NG-ZORRO-Antd分页组件绑定API返回数据
优惠活动
大模型
产品
解决方案
定价
更多

在Angular中如何使用NG-ZORRO-Antd分页组件绑定API返回数据

解决方法

你当前的问题是直接遍历了全量数据集,没有做分页切片,导致分页组件和数据展示逻辑脱节,按两种常用业务场景实现即可:

提示:如果总数据量大于1000条,推荐使用后端分页方案,减少首次加载等待时间。


场景1:前端全量分页(API一次性返回所有人员数据)

适合数据量小的场景,所有数据一次拉取到前端,前端自行计算切片展示对应页数据

第一步:组件TS文件配置

// 定义核心分页变量
currentPage = 1;
pageSize = 10;
total = 0;
// 分页后用于页面渲染的数据集,不要直接用全量的peopleHome渲染
paginatedCourses: any[] = [];
// 存储接口返回的全量数据集
peopleHome: any[] = [];

// 接口请求成功拿到全量数据后的处理
getPeopleHomeData() {
  this.yourApiService.getList().subscribe(res => {
    this.peopleHome = res;
    this.total = res.length;
    // 初始化第一页展示数据
    this.updatePaginatedData();
  })
}

// 切片计算当前页要展示的数据
updatePaginatedData() {
  const startIndex = (this.currentPage - 1) * this.pageSize;
  const endIndex = startIndex + this.pageSize;
  this.paginatedCourses = this.peopleHome.slice(startIndex, endIndex);
}

// 分页切换回调
onPageChange(page: number) {
  this.currentPage = page;
  this.updatePaginatedData();
}

第二步:修改HTML模板

<!-- 遍历分页后的数据集,不是全量的peopleHome -->
<div class="col-md-6 col-lg-4 col-xl-3" *ngFor="let course of paginatedCourses"> 
    <div class="card-blog">
        <a href="#">
            <img src="../assets/images/image10.jpg" alt="" class="img-blog" />
        </a>
        <div class="card">
            <a href="#">
                <h4 class="title-blog">{{course.people_title}}</h4>
            </a>
        </div>
    </div>
</div>
<!-- 绑定分页参数和切换事件 -->
<nz-pagination 
  [nzPageIndex]="currentPage" 
  [nzTotal]="total" 
  [nzPageSize]="pageSize"
  (nzPageIndexChange)="onPageChange($event)"
> </nz-pagination>

场景2:后端分页(每次翻页调用接口获取对应页数据)

适合数据量大的场景,每次翻页仅拉取当前页需要的数据集

第一步:组件TS文件配置

currentPage = 1;
pageSize = 10;
total = 0;
// 直接用这个数组渲染页面,每次翻页都会更新为接口返回的当前页数据
paginatedCourses: any[] = [];

// 封装分页请求方法,页面初始化和翻页时直接调用
getCourseList(page = this.currentPage, pageSize = this.pageSize) {
  // 调用接口时传递当前页码和每页条数,和后端约定好参数名即可
  this.yourApiService.getPageList({ page, pageSize }).subscribe(res => {
    this.paginatedCourses = res.list; // 接口返回的当前页数据
    this.total = res.total; // 接口返回的总数据条数
  })
}

// 分页切换回调
onPageChange(page: number) {
  this.currentPage = page;
  this.getCourseList(page);
}

第二步:HTML模板

和场景1的HTML代码完全一致即可。

内容的提问来源于stack exchange,提问作者S Oluwafemi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 17:45:03