如何使用实体框架核心在角度上进行服务器端分页

时间:2019-03-29 08:58:47

标签: angular asp.net-core entity-framework-core

我跳过并获取Controller类中的数据,如何在角度上进行分页

我的控制器类

public IEnumerable<ScrapeTime> scrapeTime(int? page, int pagesize=10)
  {
var countDetails = _context.ScrapeTime.Count();
 return _context.ScrapeTime.Skip((page ?? 0) * pagesize).Take(pagesize).ToList();
}

我的component.ts文件

constructor(http: HttpClient,  @Inject('BASE_URL') baseUrl: string) {

      http.get<scrapeTime[]>(baseUrl + 'api/ScrapeTime/ScrapeTime').subscribe(result => {

        this.Time = result;

      }, error => console.error(error));
  }

输出将仅在侧面显示10个数据,我需要对所有数据进行分页。

1 个答案:

答案 0 :(得分:0)

请按照以下步骤实现您的要求:

  1. 定义一个模型,该模型将返回项目数和项目详细信息:

    public class PageResult<T>
    {
        public int Count { get; set; }
        public int PageIndex { get; set; }
        public int PageSize { get; set; }
        public List<T> Items { get; set; }
    }
    
  2. 控制器操作

    public PageResult<ScrapeTime> scrapeTime(int? page, int pagesize = 10)
    {
        var countDetails = _context.ScrapeTime.Count();
        var result = new PageResult<ScrapeTime> {
            Count = countDetails,
            PageIndex = page ?? 1,
            PageSize = 10,
            Items = _context.ScrapeTime.Skip((page - 1 ?? 0) * pagesize).Take(pagesize).ToList()
        };
        return result;
    }
    
  3. 角度模型

    class PageResult<T>
    {
        count: number;
        pageIndex: number;
        pageSize: number;
        items: T[];
    }
    
  4. 角向动作

    export class FetchDataComponent {
    private http: HttpClient;
    private baseUrl: string;
    public Time: scrapeTime[];
    public pageNumber: number = 1;
    public Count: number;
    constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
        this.http = http;
        this.baseUrl = baseUrl;
    
        http.get<PageResult<scrapeTime>>(baseUrl + 'api/ScrapeTime/ScrapeTime').subscribe(result => {
        this.Time = result.items;
        this.pageNumber = result.pageIndex;
        this.Count = result.count;
        }, error => console.error(error));
    }
    
    public onPageChange = (pageNumber) => {
        this.http.get<PageResult<scrapeTime>>(this.baseUrl + 'api/ScrapeTime/ScrapeTime?page=' + pageNumber).subscribe(result => {
        this.Time = result.items;
        this.pageNumber = result.pageIndex;
        this.Count = result.count;
        }, error => console.error(error));
    }
    }
    
  5. 查看

    <table>
        <tr *ngFor="let item of Time | paginate: { itemsPerPage: 10, currentPage: pageNumber, totalItems:Count }">
            <!-- content here -->
            <td>{{ item.id }}</td>
            <td>{{ item.name }}</td>
        </tr>
        <pagination-controls (pageChange)="onPageChange($event)"></pagination-controls>
    </table>
    

如果您对角度分页有任何疑问,请遵循ngx-pagination