在Angular中,实现服务器端分页通常需要使用一个后端API来查询数据库并返回特定页的数据。可以使用ngx-pagination库作为Angular中前端的分页解决方案。
首先,在Angular项目中安装ngx-pagination库:
npm install ngx-pagination --save
接下来,在需要实现分页的组件中引入ngx-pagination库:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { PaginationInstance } from 'ngx-pagination';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html'
})
export class MyComponent {
data: any[];
config: PaginationInstance = {
id: 'advanced',
itemsPerPage: 10,
currentPage: 1
};
constructor(private http: HttpClient, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
// 获取路由参数中的当前页码
this.activatedRoute.queryParams.subscribe(params => {
if (params['page']) {
this.config.currentPage = params['page'];
}
this.getSomeData();
});
}
getSomeData() {
// 使用HttpClient实例从后端获取数据
this.http.get('https://my-api.com/data', { params: { page: this.config.currentPage } })
.pipe(
// 如果发生错误,则抛出错误信息
catchError(error => {
return throwError(error.message || error);
}),
// 对返回的结果进行解析并返回数据数组
map(response => response['data'])
)
.subscribe(data => {
this.data = data;
});
}
}
然后,在HTML模板中添加ngx-pagination指令,并为其传递配置对象:
- {{item.name}}