下面是一个使用Angular 7的示例代码,展示如何使用路由为API数据创建简单分页:
pagination.service.ts
的服务,用于处理分页逻辑:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PaginationService {
private apiUrl = 'https://api.example.com/data'; // 替换为实际的API地址
constructor(private http: HttpClient) { }
getPage(pageNumber: number, pageSize: number): Observable {
const url = `${this.apiUrl}?_page=${pageNumber}&_limit=${pageSize}`;
return this.http.get(url);
}
}
pagination.service.ts
服务获取分页数据。创建一个名为pagination.component.ts
的组件:import { Component, OnInit } from '@angular/core';
import { PaginationService } from './pagination.service';
@Component({
selector: 'app-pagination',
templateUrl: './pagination.component.html',
styleUrls: ['./pagination.component.css']
})
export class PaginationComponent implements OnInit {
data: any[] = [];
pageNumber = 1;
pageSize = 10;
totalItems = 0;
constructor(private paginationService: PaginationService) { }
ngOnInit() {
this.getPage(this.pageNumber);
}
getPage(pageNumber: number) {
this.paginationService.getPage(pageNumber, this.pageSize)
.subscribe(response => {
this.data = response;
this.totalItems = Number(response.headers.get('X-Total-Count'));
});
}
onPageChange(pageNumber: number) {
this.getPage(pageNumber);
}
}
pagination.component.html
的HTML模板文件,用于显示分页数据和页码:
{{ item.name }}
app.module.ts
中,将HttpClientModule
添加到imports
数组中,以便可以使用HttpClient
服务:import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
HttpClientModule
],
// ...
})
export class AppModule { }
请确保根据你的实际需求进行修改和调整。这只是一个简单的示例,你可以根据实际情况进行更改。