Retrieve information for the designated page exclusively

When retrieving data from the backend using a service, I encounter an issue where the system may slow down if 2000 records are returned in one request. To address this, I would like to display only 10 records per page and fetch the next 10 records with each click on the next page. Should this implementation be done on the backend or frontend? As a beginner, I appreciate any guidance you can provide.

HTML Code

<div class="row clearfix" [@routerTransition]>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
    <div class="card main-content" >
        <div class="header">
            <h2>
                {{l('Schools')}}
            </h2>
            <ul class="header-dropdown m-r--5">
                <i class="fa fa-spin fa-spinner" *ngIf="isTableLoading"></i>
                <li class="dropdown">
                    <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                        <i class="material-icons">more_vert</i>
                    </a>
                    <ul class="dropdown-menu pull-right">
                        <li><a href="javascript:void(0);" class=" waves-effect <waves-block></waves-block>" (click)="refresh();"><i class="material-icons">refresh</i> Refresh</a></li>
                    </ul>
                </li>
            </ul>
        </div>
        <div class="body table-responsive" style="padding-bottom: 40px">
            <table class="table table-hover table-striped" >
                <thead>
                    <tr>
                        <th>{{l('Name')}}</th>
                        <th>{{l('Registration Number')}}</th>
                        <th>{{l('Enrollment Type')}}</th>
                        <th>{{l('Entity Type')}}</th>
                        <th>{{l('Location')}}</th>
                        <th>{{l('Actions')}}</th>


                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let school of schoollists | paginate: { id: 'server', itemsPerPage: pageSize, currentPage: pageNumber, totalItems: totalItems }; let i = index">
                        <td>{{school.name}}</td>
                        <td>{{school.registrationNumber}}</td>
                        <td>{{school.educationType}}</td>
                        <td>{{school.administrativeType}}</td>
                        <td>{{school.county}}<span>,</span>{{school.city}}<span>,</span>{{school.district}}</td>

                        <td class="dropdown">
                            <a href="javascript:void(0);" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                                <i class="material-icons">menu</i>
                            </a>
                            <ul class="dropdown-menu pull-right">
                                <li *ngIf="supportAdminCheck"><a class="waves-effect waves-block" (click)="editSchool(school.schoolTenantName)"><i class="material-icons">create</i>Edit</a></li>
                                <li *ngIf="supportAdminCheck"><a href="javascript:void(0);" class="waves-effect waves-block" (click)="delete(school)"><i class="material-icons">delete_sweep</i>Delete</a></li>
                                <li><a class="waves-effect waves-block" (click)="schoolDetail(school.schoolTenantName)"><i class="material-icons">details</i>View</a></li>
                            </ul>
                        </td>
                    </tr>
                </tbody>
            </table>

           <div class="text-align: center;" *ngIf="totalItems > pageSize">
                <pagination-controls (pageChange)="getDataPage($event)" id="server"></pagination-controls>
            </div>
            <!-- <br> -->
            <button type="button" data-toggle="modal" class="btn btn-primary btn-circle waves-effect waves-circle waves-float pull-right" (click)="createRole()">
                <i class="material-icons">add</i>
            </button>
        </div>
    </div>
</div>

TypeScript Code

  list(request: PagedRequestDto, pageNumber: number, finishedCallback: Function): void {
    this._schoollistService.getAll()
        .finally( ()=> {
            finishedCallback();
        })
  .subscribe((result: PagedResultDtoOfSchoolListDto)=>{
            this.schoollists = result.items;
            this.showPaging(result, pageNumber);
            this.supportAdminCheck = false;
            if (this.appSession.tenant === undefined && this._utilsService.getCookieValue(AppConsts.authorization.roleName) === 'SuperAdmin') {
                this.supportAdminCheck = true;
            } else {
                this.supportAdminCheck = false;
            }
    });

}

Answer №1

What api framework are you currently utilizing?

Many frameworks offer the ability to customize pagination (such as order criteria and number of items) which is a common feature.

Typically, pagination must be set up on the backend and accessed by the client through URLs like:

www.server.com/api/v1/my-data?page=1

To handle pagination efficiently in Angular using HttpClient, you can create a PaginationService like below:

private currentPage = 1;

getNextPage(): Observable<Data[]> {
    this.currentPage += 1;
    return this.http.get<Data[]>(API_BASE_URL + 'data' + '?page=' + this.currentPage);
}

getPreviousPage(): Observable<Data[]> {
    this.currentPage -= 1;
    return this.http.get<Data[]>(API_BASE_URL + 'data' + '?page=' + this.currentPage);
} 

goToPage(page: number): Observable<Data[]> {
    this.currentPage = page;
    return this.http.get<Data[]>(API_BASE_URL + 'data' + '?page=' + this.currentPage);
}

Make sure to register your service as a Provider in your NgModule (or at the component level if required).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with Angular 4 functionality on Tizen Smart TV

After developing a basic Angular4 application, I transformed it into a Tizen web app. Surprisingly, the app functions properly on major browsers like Safari, Chrome, and Firefox, but only displays an empty page with an empty () element. During debugging i ...

What is the best way to display the arrows on a sorted table based on the sorting order in Angular?

I need assistance with sorting a table either from largest to smallest or alphabetically. Here is the HTML code of the section I'm trying to sort: <tr> <th scope="col" [appSort]="dataList" data-order ...

Enumerated type alias in Typescript

Within my typings file, I have the following: declare namespace Somatic { enum PropType { html, object, css } } In a separate file named index.ts, I create a shorter alias for this enum like so: type PropType = Somatic.Pr ...

What is the best approach for testing the TypeScript code below?

Testing the following code has been requested, although I am not familiar with it. import AWS from 'aws-sdk'; import db from './db'; async function uploadUserInfo(userID: number) { const user = db.findByPk(userID); if(!user) throw ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

The issue of Angular 15 Childcomponent failing to refresh the user interface despite input modifications

Within this component, I have two child components: <span>Timings:</span> <sir-project-fasetiming [faseTiming]="projectTiming.timingInitiatie" (faseTimingChanged)="faseTimingChanged($event, 'timingInitiatie')"&g ...

Problem with ngStyle: Error indicating that the expected '}' is missing

I encountered an error in the Chrome console when trying to interpret the code below: <div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat&ap ...

Having trouble resolving all parameters for the service in an Angular2 test with Jasmine mocking

I am currently attempting to create a mock service for testing purposes: Production: @Injectable() export class UserService extends DtoService { // irrelevant details here. } @Injectable() export abstract class DtoService { constructor(private h ...

Using Typescript to transform a list into function arguments

My current challenge involves a set of arguments structured like so: const args: FeatureEventArg[] = [ { name: 'username', type: 'string', }, { name: 'message', type: 'string', }, { name ...

Integrating concealed elements into jspdf

I am currently working on incorporating a hidden div into my jspdf file. Utilizing html2canvas for this purpose, I find it necessary to briefly make the div visible, add it to the pdf, and then hide it again. This method is not ideal as the content moment ...

Unable to personalize map controls in OpenLayer mapping system

Having trouble styling custom map controls with CSS selectors .ol-zoom-in and .ol-zoom-out. Any suggestions on how to customize them? export class CustomMapControlsComponent implements OnInit { map: Map | undefined; constructor() {} ngOnInit() ...

Angular animation triggered when a specific condition is satisfied

I am working on an animation within my Angular application @Component({ selector: 'app-portfolio', templateUrl: 'portfolio.page.html', styleUrls: ['portfolio.page.scss'], animations: [ trigger('slideInOut&apo ...

How can we track and record NaN values in JavaScript/TypeScript as they occur in real-time?

Is there a reliable method to identify and prevent NaN values during runtime, throughout all areas of the application where they might arise? A) Are there effective linting tools available to alert about possible occurrences of NaN values within specific ...

Is there a more efficient method to tally specific elements in a sparse array?

Review the TypeScript code snippet below: const myArray: Array<string> = new Array(); myArray[5] = 'hello'; myArray[7] = 'world'; const len = myArray.length; let totalLen = 0; myArray.forEach( arr => totalLen++); console.log(& ...

It is impossible for me to invoke a method within a function

I am new to working with typescript and I have encountered an issue while trying to call the drawMarker() method from locateMe(). The problem seems to be arising because I am calling drawMarker from inside the .on('locationfound', function(e: any ...

The potential issue of undefined objects in TypeScript when utilizing computed properties in Vue3

I've attempted adding a ? after each word and also experimented with the following code: const totalNameLenght = computed(() => { if (userFirstnameLenght.value && userLastnameLenght.value){ return userFirstnameLenght.value + u ...

Adjust the background color of the header as you scroll

Seeking assistance in adjusting the background color of my header upon scrolling. This is my current implementation: header.component.ts export class HeaderComponent { ngOnInit(): void { const header = document.querySelector('.header'); ...

How can we efficiently determine if a background image is broken in Angular 5 and substitute it with a default image?

When working with Angular 2+, we often use the <img> tag to display images using a syntax like <img [src]="myDp" (error)="myDp='assets/media/user/default_dp.jpg'">, where myDp contains the relative path to the image on the server. Is ...

What is the proper way to specify the type for a proxy that encapsulates a third-party class?

I have developed a unique approach to enhancing Firestore's Query class by implementing a Proxy wrapper. The role of my proxy is twofold: If a function is called on the proxy, which exists in the Query class, the proxy will direct that function call ...

Ways to implement a package designed for non-framework usage in Vue

Alert This may not be the appropriate place to pose such inquiries, but I am in need of some guidance. It's more about seeking direction rather than a definitive answer as this question seems quite open-ended. Overview I've created a package th ...