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

Dynamic Mat-select-trigger that automatically adjusts its size to fit the content

Currently, I am experimenting with an Angular Mat-Select that allows multiple selections. To display the selected values in the value field, I have implemented a custom Mat-Select-Trigger. My goal is to enable automatic resizing of the value field (similar ...

Initiating a GET request to execute an SQL query with specified parameters

Let me provide some background information. I am currently using Angular for the frontend and Express for the backend, while also learning how to effectively utilize both technologies. In my application, there is a parent component that generates a group ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

Tips for referencing all parameters except the last one in TypeScript

Looking for a solution similar to: how to reference all parameters except first in typescript This time, I need to access all parameters except the last one. The solution provided in that question didn't work for my specific case. Any suggestions o ...

What could be causing a custom Angular library to fail to compile after being published on npm?

I recently launched a library that I created for my team to expedite the process of developing applications specifically for the Internet of Things (IOT) sector. However, I have encountered an issue where the library compiles without errors in the demo pro ...

Error 16 occurred when attempting to ngUpgrade two different versions of Highcharts

After successfully upgrading my app to use ngUpgrade, I encountered an issue while trying to incorporate Highcharts. In the original version of the app, there was an older version of Highcharts designed for AngularJS. However, in the new hybrid app using ...

Obtain the file path relative to the project directory from a Typescript module that has been compiled to JavaScript

My directory structure is as follows: - project |- build |- src |- index.ts |- file.txt The typescript code is compiled to the build directory and executed from there. I am seeking a dependable method to access file.txt from the compiled module without ...

Aligning arguments within the function signature

Is it possible to specify in TypeScript that the method 'foo' always expects FooData, etc. for the following code snippet: const search = (data: FooData|BarData|BazData, method:"foo"|"bar"|"baz") => { //Perform some common operations retu ...

Tips for dynamically injecting HTML content in an Angular web application

I'm currently working on an angular website dedicated to a specific book. One of the features I want to include is the ability for users to select a chapter and view an excerpt from that chapter in HTML format. However, I'm facing a challenge wh ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Unable to retrieve post information from Angular using PHP

I've hit a roadblock in my Angular App where I can't seem to access the body of the post data being sent from Angular 4. Despite numerous attempts, I'm unable to retrieve this crucial information. Can anyone lend a hand in identifying the is ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

Uninitialized Array Member in Angular 8

Can anyone explain why the code snippet below is printing "undefined"? I have created several objects and intended to display the corresponding images, but after iterating through them using ngfor, nothing appeared. To investigate, I logged the array and ...

Can you explain the meaning of `((prevState: null) => null) | null`?

Upon encountering this code snippet: import { useState } from "preact/hooks"; export default function Test() { const [state, setState] = useState(null); setState('string'); } An error is thrown: Argument of type 'string' ...

What is the best way to integrate ngx-translate's pipe for global translation?

I'm currently utilizing the ngx-translate package in order to internationalize my Angular application. When translating text using the translate pipe like so: {{ 'title' | translate }} An issue arises when attempting to use this pipe in ot ...

Issue with React TypeScript: Only the first state update takes effect, despite multiple updates being made

Check out this sandbox I created here. When you leave any of the form inputs blank, I should be seeing 3 errors but instead, I only get one. Can anyone explain why this is happening? import React, { ChangeEvent, useState } from 'react'; import { ...

Resolving circular dependencies caused by APP_INITIALIZER

My AuthenticationService is responsible for loading the AngularFirestore and is loaded in the RootComponent. All app modules are lazily loaded within the RootComponent (which contains the main router-outlet). However, several sub-modules also load the Ang ...

The element "center" is not a recognized HTML tag in Angular 4

The center tag is not functioning and it says that center is an unknown element. <center> <a><img class="placeholder_img" src="img/placeholder.png"></a> </center> When I used the above HTML tags, it stated that "center i ...

Utilizing import for Ionic3 to export const with logic

While developing an app using ionic3, I encountered an issue with setting up a proxy. When running in a browser, Ionic was able to recognize the path of my proxyUrl as shown below. ionic.config.json { "name": "myApp", "app_id": "", "v2": true, "t ...