Angular列表点击按钮实现每次从API加载10条数据
实现点击加载更多学生数据功能
1. 组件类核心逻辑
在组件中维护学生列表、分页偏移量及加载状态,避免重复请求:
import { Component } from '@angular/core'; import { StudentDataService } from './student-data.service'; @Component({ selector: 'app-student-list', templateUrl: './student-list.component.html', styleUrls: ['./student-list.component.css'] }) export class StudentListComponent { studentList: any[] = []; offset = 0; isLoading = false; constructor(private studentDataService: StudentDataService) {} ngOnInit(): void { // 初始化加载第一页数据 this.loadMoreStudents(); } loadMoreStudents(): void { if (this.isLoading) return; this.isLoading = true; this.studentDataService.getStudents(this.offset).subscribe({ next: (data) => { // 追加新数据到现有列表 this.studentList = [...this.studentList, ...data]; // 更新偏移量,下次加载下一组10条数据 this.offset += 10; this.isLoading = false; }, error: (err) => { console.error('加载数据失败:', err); this.isLoading = false; } }); } }
2. 调整StudentDataService服务
让服务支持传递偏移量参数,拼接接口请求地址:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class StudentDataService { private apiUrl = '你的学生数据接口地址'; constructor(private http: HttpClient) {} getStudents(offset: number): Observable<any[]> { // 拼接offset参数,接口固定limit=10 return this.http.get<any[]>(`${this.apiUrl}?offset=${offset}&limit=10`); } }
3. HTML模板绑定事件与状态
给「加载更多」按钮绑定点击事件,根据加载状态更新按钮状态:
<div class="container mt-4"> <!-- 学生列表展示 --> <div class="row"> <div class="col-md-4 mb-3" *ngFor="let student of studentList"> <div class="card"> <div class="card-body"> <h5 class="card-title">{{student.name}}</h5> <p class="card-text">学号: {{student.id}}</p> <p class="card-text">年级: {{student.grade}}</p> </div> </div> </div> </div> <!-- 加载更多按钮 --> <div class="text-center mt-4"> <button class="btn btn-primary" (click)="loadMoreStudents()" [disabled]="isLoading" > {{ isLoading ? '加载中...' : '加载更多' }} </button> </div> </div>
关键细节说明
- 用
offset参数控制每次加载的起始位置,配合接口固定的limit=10实现分页加载。 isLoading状态变量防止用户重复点击触发多个请求。- 用扩展运算符
[...this.studentList, ...data]追加数据,避免直接修改原数组导致的变更检测异常。
内容的提问来源于stack exchange,提问作者Muhammad Anas
相关产品推荐
相关产品推荐

