How To Pagination Angular2 with Django Rest Framework API

2024/11/15 15:53:40

I am trying to create a simple blog application using Angular2 with Django Rest Framework. I am implementing pagination in Django, but I do not know how to rendering it in Angular.

API has the following structure. Entries are paginated every 5 entries.

enter image description here


ng2app/src/app/models/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
}


ng2app/src/app/services/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);}}


ng2app/src/app/services/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);}
}


ng2app/src/app/templates/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>


In such a case, please help how to implement Pagination.

Answer

After implementing pagination in the Django backend, querying the backend would return results in the following format:

"data": {"count": ,"next": "","previous": "","results": []
}

count: The total number of items returned.

next: The URL to the next items after performing pagination

previous: The URL to the previous items after you have navigated to the next. set of items

results: The items requested for from the backend, paginated obviously i.e if pagination was set to 10 items and 15 were returned, results would return 10 items on the first request, then after navigating to the URL in next, results would return the remaining 5.

Service

@Injectable({providedIn: "root"
})
export class OurService {  constructor(private http: HttpClient) {}// Here,we make our request to the backend API, this observer takes in the backend// api url as a parameter and performs a GET requestgetAllTransactions(APIUrl: string): Observable<any> {return this.http.get<>(APIUrl);}
}

Component

@Component({selector: "app-transactions",templateUrl: "./transactions.component.html",styleUrls: ["./transactions.component.scss"]
})
export class TransactionsComponent implements OnInit {transactions: Transacton[];transactionsUrl = "http://.../api/v1/transactions/"; //url to query for the transactionsnext: string;previous: string;constructor(private transactionService: TransactionService) {}ngOnInit(): void {// On component initialization, load the transactions on the pagethis.getTransactions(this.transactionsUrl);}getTransactions(url: string) {this.transactionService.getAllTransactions(url).subscribe(res => {this.transactions = res.data.results;if (res.data.next) {// set the components next transactions here from the responsethis.next = res.data.next;}if (res.data.previous) {// set the components previous transactions here from the responsethis.previous = res.data.previous;}});}// function fetches the next paginated items by using the url in the next transactionsfetchNext() {this.getTransactions(this.next);}// function fetches the previous paginated items by using the url in the previous transactionsfetchPrevious() {this.getTransactions(this.previous);}

HTML

<div class="page-buttons"><button class="btn prev" (click)="fetchPrevious()"></button><button class="btn next" (click)="fetchNext()"></button>
</div>
https://en.xdnf.cn/q/71447.html

Related Q&A

Color percentage in image for Python using OpenCV

Im creating a code which can detect the percentage of green colour from an image. . I have a little experience with OpenCV but am still pretty new to image processing and would like some help with my c…

Combination of GridSearchCVs refit and scorer unclear

I use GridSearchCV to find the best parameters in the inner loop of my nested cross-validation. The inner winner is found using GridSearchCV(scorer=balanced_accuracy), so as I understand the documentat…

stale association proxy, parent object has gone out of scope with Flask-SQLAlchemy

Ive actually never encountered this error before:sqlalchemy.exc.InvalidRequestError: stale association proxy, parent object has gone out of scopeAfter doing some research, it looks like its because the…

Automatic dictionary key resolution with nested schemas using Marshmallow

I have a Marshmallow schema where an objects use a key to refer to an object that is defined in a dictionary in another part of the structure. I want to have the key automatically resolved when deseria…

Type hinting for Django Model subclass

I have helper function for Django views that looks like this (code below). It returns None or single object that matches given query (e.g. pk=1). from typing import Type, Optionalfrom django.db.models …

How to diff the two files using Python Generator

I have one file of 100GB having 1 to 1000000000000 separated by new line. In this some lines are missing like 5, 11, 19919 etc. My Ram size is 8GB.How to find the missing elements.My idea take another …

How to resolve: attempted relative import with no known parent package [duplicate]

This question already has answers here:Attempted relative import with no known parent package [duplicate](4 answers)Closed 2 years ago.I have a bare bones project structure with mostly empty python fil…

How to create a figure of subplots of grouped bar charts in python

I want to combine multiple grouped bar charts into one figure, as the image below shows. grouped bar charts in a single figure import matplotlib import matplotlib.pyplot as plt import numpy as nplabels…

Python Pillow: Make image progressive before sending to 3rd party server

I have an image that I am uploading using Django Forms, and its available in the variable as InMemoryFile What I want to do is to make it progressive.Code to make an image a progressiveimg = Image.open…

Python - Should one start a new project directly in Python 3.x?

What Python version can you please recommend for a long-term (years) project? Should one use 2.6+ or 3.x is already stable? (only standard libraries are required)UPDATE: according to the answers belo…