Querying the api for data using Angular when paginating the table

Currently, I have a table that retrieves data from an API URL, and the data is paginated by default on the server. My goal is to fetch new data when clicking on pages 2, 3, etc., returning the corresponding page's data from the server.

I am using ant design for my table, but I find their callback methods in the documentation confusing. Therefore, I am seeking assistance to achieve this functionality. Check out the documentation for reference.

Code

Script

listOfData: DataItem[] = []
limit = ''
page = ''
pages = ''

ngOnInit(): void {
  this.getList();
}

getList() {
  this.helpdeskService.getList().subscribe((res) => {
      this.listOfData = res.data;

      this.limit = res.limit //10
      this.page = res.page  //1
      this.pages = res.pages  //2

      if(this.listOfData.length > 0){
        this.isSpinning = false;
      } else {
        this.isSpinning = true;
      }
  },
  (error) => {
    console.log('data', error)
  });
}

HTML

<ng-template #rangeTemplate let-range="range" let-total>Display {{ range[1] }} of {{ total }} items </ng-template>
<nz-table
  #filterTable
  nzShowSizeChanger
  (nzCurrentPageDataChange)="onCurrentPageDataChange($event)"
  [nzData]="listOfData" class="kit__utils__table mb-4"
  [nzPageSizeOptions]="[5, 10, 20, 30, 40]"
  [nzPageSize]="limit"
  [nzPageIndex]="page"
  [nzShowTotal]="rangeTemplate">
  <thead>
  //...
  </thead>
  <tbody>
    ..//
  </tbody>
</nz-table>

Can anyone assist with implementing this feature?

Answer №1

Whenever the pageIndex changes, remember to include a Callback function

Insert the following code snippet into your template:

[nzTotal]="totalPages" (nzPageIndexChange)="onPageIndexChange($event)"

For HTML:

<ng-template #rangeTemplate let-range="range" let-total>Display {{ range[1] }} of {{ total }} items </ng-template>
<nz-table
  #filterTable
  nzShowSizeChanger
  (nzCurrentPageDataChange)="onCurrentPageDataChange($event)"
  (nzPageIndexChange)="onPageIndexChange($event)"
  [nzData]="listOfData" class="kit__utils__table mb-4"
  [nzPageSizeOptions]="[5, 10, 20, 30, 40]"
  [nzPageSize]="limit"
  [nzPageIndex]="page"
  [nzTotal]="totalPages"
  [nzFrontPagination]="false" 
  [nzShowPagination]="true" 
  [nzShowTotal]="rangeTemplate">
  <thead>
  //...
  </thead>
  <tbody>
    ..//
  </tbody>
</nz-table>

Add the following code to your TypeScript file:

getList(pageIndex: number | null): Observable < any > {
  const endpoint=pageIndex? `${this.env.HELPDESK_LIST}?start=${pageIndex}&limit=5`: this.env.HELPDESK_LIST
  const tokenPromise =
    this.token === undefined
      ? store.get('accessToken')
      : Promise.resolve(this.token);

  return from(tokenPromise).pipe(
    switchMap((token) => {
      this.token = this.token;
      const httpOptions = {
        headers: new HttpHeaders({
          Accept: 'application/json, text/plain',
          'Content-Type': 'application/json',
          Authorization: 'Token ' + this.token,
        }),
      };
      return this.http
        .get(endpoint, httpOptions)
        .pipe(map((data) => data));
    })
  );
}

getList(pageIndex) {
  this.helpdeskService.getList(pageIndex).subscribe((res) => {
      this.listOfData = res.data;

      this.limit = res.limit //10
      this.page = res.page  //1
      this.totalPages = res.total
      this.pages = res.pages  //2

      if(this.listOfData.length > 0){
        this.isSpinning = false;
      } else {
        this.isSpinning = true;
      }
  },
  (error) => {
    console.log('data', error)
  });
}
onPageIndexChange(pageIndex: number | null){
    console.log(pageIndex) // get you the page index
    // make api call requesting data for only that page index
   this.getList(pageIndex)

  }

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

What is the reason behind a TypeScript compiler error being triggered by an 'if-else' statement, while a ternary operator construct that appears identical does not raise any errors?

My function is designed to either return a value of IDBValidKey or something that has been converted to IDBValidKey. When I use the ternary operator to write the function, it works fine. However, if I try to write it as an if-else statement, it causes a co ...

Grails: Javascript function for updating the image source is unresponsive

I have a situation where I need to change the src of an img based on a certain condition. The condition is returning true as expected, as confirmed by an alert() that I added previously. However, the function responsible for changing the src of the img and ...

Updating a section of a component using another component

I need to update the Header.vue component from the ConfirmCode Component when the confirm method is called When a user logs in with axios ajax, I want to refresh the li element of the header component Appointment.vue: <send-sms-modal@clickClose="setS ...

The Best Way to Filter Mongo Documents Using Nested Objects

Is there a way to locate a room by its ID and confirm that it includes the current player? Within my mongodb database, I have a collection of rooms that contain players who are users. const RoomSchema = new Schema({ players: [{ type: Schema.Types.Objec ...

What is the best way to implement Axios for data fetching in Gatsby's useStaticQuery function?

One way to fetch data in Gatsby is by using GraphQL, like in the following example: import { graphql, useStaticQuery } from "gatsby" const IndexPage = () => { const gatsbyRepoData = useStaticQuery(graphql` { github { repo ...

"Encountering an issue with Angular's npm run serve:ssr

When executing npm run serve:ssr, the terminal is flooded with a stream of minified characters which ultimately leads to a failure with this error message: Error: ENOENT: no such file or directory, open 'google/protobuf/api.proto' at Object.open ...

Step-by-step guide on how to display chosen values in a multi-select dropdown menu

How can I dynamically select values in a multi-select box based on an array using Vue.js? I've attempted a solution but it's not working as expected. Any suggestions or help would be greatly appreciated. <div id="app"> <select class="m ...

Using Angular 2 for two-way binding with input masking

Encountering an issue with ng2 and inputmask. Here is the code snippet that's causing trouble: <div class="form-group col-sm-7"> <label class="control-label" for="sender-phone">Phone *</label> <input type="text" [(ngModel) ...

Please refresh the page after acknowledging the error

I am facing an issue with my PHP page that triggers a javascript alert upon encountering an error. if (strpos($this->color,':') !== false) { echo '<script type="text/javascript">alert("Please use the RBG format of 255:2 ...

What is the best way to combine an array into a single string and insert it into a textarea with line breaks?

My current goal involves executing the following code with no success: var arr = ['one', 'two','three'] const mydiv = document.createElement('textarea') mydiv.innerText = arr.join('\r\n') docum ...

The delay in loading HTML content using FOSJsRoutingBundle and Ajax for a specific route parameter (ID)

I'm using FOSjSrouting in my symfony2.7 project. This is the code in my html.twig view: <table> <!--table header code ...etc... --> <tbody> {% for currentData in arrayData %} <tr> <td>{{ currentData. ...

Conceal element when unchecked

There is a checkbox pre-selected labeled "Use profile address" with the address displayed below. If the customer unchecks the checkbox, the address that was shown before will disappear and a new input field for adding a different address will appear. I a ...

Enhancing appearance with $refs?

Having trouble adding style to the $refs attribute. I keep getting an error message saying "Cannot set property 'cssText' of undefined." Is there a way to accomplish this task? I haven't come across anything similar to this issue before. th ...

What could be the reason for react-query searching for dispatch even when redux is not activated or present in the component?

I am currently working on a component that is supposed to fetch logged-in users from the server. Despite Swagger indicating that the server code returns correctly, the component fails to make the necessary fetch request when loaded. Below is the code snip ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

Exploring ways to personalize Angular UI Bootstrap tabs to match the styling of Angular Material tabs

Currently, I am utilizing Angular UI Bootstrap in my project. <html ng-app="ui.bootstrap.demo"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script> <script src="//ajax.googleapis.co ...

Issue with executing Jquery in PUG file: The $ sign is not being recognized despite jQuery being imported

I am encountering an issue where my jQuery code placed inside a pug template is not executing as expected. Despite including the jQuery file, when trying to run a jQuery function, I receive the error below: 40| P 41| ...

React Redux Connect MapState not refreshing when filtering an item from a list

It seems like I may have misunderstood something or made a mistake when trying to subscribe to changes on a specific item within a collection in my store. My component isn't receiving updates unless I directly subscribe to the list. The following cod ...

Utilizing AJAX to load a WAV file

One of the tasks I'm working on involves a collection of audio files. When a file from this list is clicked, I want JavaScript to load and display the waveform of that specific audio file. The following function is responsible for drawing the wavefor ...

Link commitments and ornament an entity

I'm struggling to grasp the concept of promises, specifically in chaining them and enhancing an object with data fetched from various endpoints. For instance: In my node-express application, I have the following code //controller.js export const ge ...