如何使用Django Rest Framework API分页Angular2

xKx*_*xKx 5 python django pagination angular

我正在尝试使用Angular2和Django Rest Framework创建一个简单的博客应用程序.我在Django中实现分页,但我不知道如何在Angular中渲染它.

API具有以下结构.条目每5个条目分页.

在此输入图像描述


ng2app/src目录/应用/模型/ entries.model.ts

export interface IEntries {
  count: any,
  next: any,
  previous: any,
  results: IResults[]
}

export interface IResults {
  title: string,
  body: string,
  created_at: any,
  updated_at: any
}
Run Code Online (Sandbox Code Playgroud)


ng2app/src目录/应用/服务/ entries.service.ts

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import 'rxjs/add/operator/toPromise';

import { IEntries } from '../models/entries.model';

@Injectable()
export class EntriesService {

  constructor(
    private http: Http
  ){
  }

  getEntries(page: number){
    return this.http
      .get(`http://127.0.0.1:8000/api/entries/?limit=5&offset=` +((page * 5)-5))
      .toPromise()
      .then(response => response.json())
      .catch(this.handleError);
  }

  private handleError(error: any) {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}
Run Code Online (Sandbox Code Playgroud)


ng2app/src目录/应用/服务/ entries.component.ts

import { Component, OnInit } from '@angular/core';
import { EntriesService } from '../services/entries.service';
import { IEntries } from '../models/entries.model';


@Component({
  selector: 'my-entries',
  templateUrl: '../templates/entries.component.html',
  styleUrls: ['../static/entries.component.css']
})
export class EntriesComponent implements OnInit{
  title = 'entries';
  entries: IEntries[] = [];
  error: any;

  public constructor(
    private entriesService: EntriesService,
  ){}

  getEntires(page :number) {
    this.entriesService
      .getEntries(page)
      .then(entries => this.entries = entries)
      .catch(error => this.error = error);
  }

  ngOnInit() {
    this.getEntires(1);
  }
}
Run Code Online (Sandbox Code Playgroud)


ng2app/src目录/应用/模板/ entries.component.html

<div class="container">
  <h2>{{title}}</h2>
  <div class="panel panel-default" *ngFor="let results of entries.results">
    <div class="panel-heading"><a href="detail/{{ results.id }}">{{ results.title }}</a></div>
    <div class="panel-body pre-wrap" ng-bind="multiLineText">{{ results.body }}</div>
    <div class="panel-footer">{{ results.created_at | date}}</div>
  </div>
  <nav *ngIf="entries.count > 5">
      (I want to display pagination here)
  </nav>
</div>
Run Code Online (Sandbox Code Playgroud)


在这种情况下,请帮助如何实现分页.

Jun*_*tin 0

您可以尝试ngx-pagination在 Angular 2+ 中进行分页。