在【Ng Alain】官方示例源碼中,關於pagination分頁控件的代碼如下:
<ng-template #pagination>
<nz-pagination [nzTotal]="50" [nzPageSize]="5" (nzPageIndexChange)="getData()"></nz-pagination>
</ng-template>
其實,這並不是真實的業務用法,並沒有反應實際的業務數據,我們對這段代碼稍微改造一下,看下Ng Alain實際應該使用分頁控件。
首先增加一個雙向綁定,[(nzPageIndex)]="pageIndex"
,用以記錄頁面實際頁碼,實際上,nzPageSize和nzTotal都應該雙向綁定,簡單起見,我們僅設置當前頁面pageIndex
爲雙向綁定。
<ng-template #pagination>
<nz-pagination [nzTotal]="36" [nzPageSize]="5" [(nzPageIndex)]="pageIndex" (nzPageIndexChange)="getData()"></nz-pagination>
</ng-template>
後臺代碼getData()
增加pageIndex
和pageSize
參數,當點擊不同的頁碼時顯示不同的數據,注意,這裏記錄總數我們假定爲36
getData() {
console.log("nzPageIndex is " + this.pageIndex);
this.loading = true;
this.http.get('/api/list?pageIndex=' + this.pageIndex + '&pageSize=' + this.pageSize, {count: 5}).subscribe((res: any) => {
console.log('basic list res is '+JSON.stringify(res));
this.data = res;
this.loading = false;
});
}
接下來調整我們的接口代碼/api/list
- Controller接口定義
@GetMapping("list")
public List<NgList> getList(@RequestParam(value = "pageIndex", required = false) Integer pageIndex
, @RequestParam(value = "pageSize", required = false) Integer pageSize) {
return apiService.getList(pageIndex, pageSize);
}
- 接口實現ServiceImpl
@Override
public List<NgList> getList(Integer pageIndex, Integer pageSize) {
if (pageIndex == null) {
pageIndex = 1;
}
if (pageSize == null) {
pageSize = 5;
}
List<NgList> ngLists = new ArrayList<>();
int start = (pageIndex - 1) * pageSize + 1;
int end = pageIndex * pageSize;
if (end > 36) {
end = 36;
}
for (int i = start; i <= end; i++) {
ngLists.add(
NgList.builder()
.id("FakeList-" + i)
.owner(user.get(i % 10))
.title("【" + i + "】" + titles.get(i % 8))
.avatar(avatars.get(i % 8))
.cover(covers.get(i % 4))
.status(statuses.get(i % 3))
.percent((int) Math.ceil(Math.random() * 50) + 50)
.logo(avatars.get(i % 8))
.href("http://github.com")
.updatedAt(Calendar.getInstance().getTime().getTime())
.createdAt(Calendar.getInstance().getTime().getTime())
.subDescription("【" + i + "】" + desc.get(i % 5))
.description("月落烏啼霜滿天,江楓漁火對愁眠")
.activeUser((int) Math.ceil(Math.random() * 100000) + 100000)
.newUser((int) Math.ceil(Math.random() * 100000) + 100000)
.star((int) Math.ceil(Math.random() * 100000) + 100000)
.like((int) Math.ceil(Math.random() * 100000) + 100000)
.message((int) Math.ceil(Math.random() * 100000) + 100000)
.content("段落示意:螞蟻金服設計平臺 ant.design,用最小的工作量,無縫接入螞蟻金服生態,提供跨越設計與開發的體驗解決方案。螞蟻金服設計平臺 ant.design,用最小的工作量,無縫接入螞蟻金服生態,提供跨越設計與開發的體驗解決方案。")
.member(List.of(
Map.of("avatar", "https://gw.alipayobjects.com/zos/rmsportal/ZiESqWwCXBRQoaPONSJe.png", "name", "趙小小")
, Map.of("avatar", "https://gw.alipayobjects.com/zos/rmsportal/tBOxZPlITHqwlGjsJWaF.png", "name", "王昭君")
, Map.of("avatar", "https://gw.alipayobjects.com/zos/rmsportal/sBxjgqiuHMGRkIjqlQCd.png", "name", "趙飛燕")
))
.build()
);
}
return ngLists;
}
構建啓動,我們看下實際效果如下:
-
第一頁內容
-
第二頁內容