/pagination.component.ts Secret
Created
December 25, 2020 15:45
Star
You must be signed in to star a gist
3. Emit response data and other parameters to parent component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Current page number | |
currentPageNumber: number = 1; | |
// Total records count | |
totalRecordsCount: number = 0; | |
// Total pages | |
totalPages: number = 0; | |
// Pager | |
pager: any = {}; | |
constructor(private http: HttpClient, private pagerService: PagerService) {} | |
// API route | |
@Input() apiRoute: string = ''; | |
// Records per page | |
@Input() recordsPerPage: number = 0; | |
// Response data | |
@Output() responseData = new EventEmitter<any[]>(); | |
// Loading | |
@Output() loading = new EventEmitter<boolean>(); | |
// Fetch new page data | |
next() { | |
this.getData(this.currentPageNumber + 1) | |
} | |
// Fetch previous page data | |
prev() { | |
this.getData(this.currentPageNumber - 1) | |
} | |
// Fetch data from API | |
getData(pageNo: any) { | |
this.loading.emit(true); | |
this.currentPageNumber = Number(pageNo); | |
let finalPath = `${this.apiRoute}?pageNumber=${this.currentPageNumber}&recordsPerPage=${this.recordsPerPage}`; | |
this.http.get(finalPath).subscribe( | |
(response: any) => { | |
this.totalRecordsCount = response.count; | |
this.responseData.emit(response.data); | |
this.totalPages = Math.ceil(response.count / this.recordsPerPage); | |
this.setPagination(this.currentPageNumber); | |
this.loading.emit(false); | |
}, | |
(error) => { | |
this.loading.emit(false); | |
alert(error.message); | |
} | |
); | |
} | |
// Set pagination data and pager data | |
setPagination(pageNo: any) { | |
pageNo = Number(pageNo); | |
this.currentPageNumber = pageNo; | |
this.pager = this.pagerService.getPager( | |
this.totalRecordsCount, | |
pageNo, | |
this.recordsPerPage | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment