我需要为从 SQL 数据库中获取数据的表实现服务器分页,我需要将响应中的数据保存为数字 (count:number) 但如果我检查 consolelog 中的 totalItems 值未定义。
如果我将 totalItems 更改为 100,除了没有显示正确的页数外,一切都几乎完美。
GET 方法的返回值只是那个数字。所以我必须获取该数字并将其放入 count:number 或将该数字作为 typescript 方法的值返回。
component.ts
count:number;
constructor(
private service: UserService
) {
this.config = {
itemsPerPage: 10,
currentPage: 1,
totalItems : this.service.getPaginationInfo()
};
}
service.ts
getPaginationInfo() {
this.http.get(this.BaseURL + '/Count?id=' + this.userIdString)
.subscribe(result => {
this.count = result as number},
(err) => {
console.log(err);
}
);
return this.count;
}
ASP .NET Core 方法:
[HttpGet]
public int GetContactCount(string id)
{
return _context.ContactDetails.Count(w => w.UserId == id);
}
Get 方法返回:
30
HTML:
<table class="table table-hover text-white transparent-dark">
<tr *ngFor="let contact of service.list | paginate: config">
<td data-toggle="modal" data-target="#UpdateContactModal" (click)="populateForm(contact)">{{contact.Name}}</td>
<td data-toggle="modal" data-target="#UpdateContactModal" (click)="populateForm(contact)">{{contact.PhoneNumber}}
</td>
<td>
<i class="far fa-trash-alt fa-lg text-danger" (click)="this.service.onDelete(contact.ContactId)"></i>
</td>
</tr>
</table>
<pagination-controls (pageChange)="pageChanged($event)" class="center-footer text-white"></pagination-controls>
最佳答案
你的 getPaginationInfo()
是一个异步函数。你不能返回一个简单的 number
类型。
要解决该问题,请更改服务以返回 Observable<number>
:
getPaginationInfo() { return this.http.get<number>(this.BaseURL + '/Count?id=' + this.userIdString);.subscribe( result => { this.count = result as number}, (err) => { console.log(err); } ); return this.count;}
And change the invocation in the following way:
this.config = {
itemsPerPage: 10,
currentPage: 1,
totalItems : 0
};
this.service.getPaginationInfo().subscribe(
result => {
this.config.totalItems = result;
},
(err) => { console.log(err); }
);
关于database - 服务器分页 : Typescript Save GET method data to number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907589/