Skip to main content

Add pagination with URL query parameters

Step 12 — Adding URL Query Parameters to the HttpClient get() Method

In this step, we'll start adding the logic for implementing pagination in our example application. We'll see how to use URL query parameters via [fromString and HttpParams](https://angular.io/guide/http#use-fromstring-to-create-httpparams) to provide the appropriate values for the the _page and _limit parameters of the /products endpoint of our JSON REST API server for getting paginated data.

Open the src/app/data.service.ts file and start by adding the following the import for HttpParams:

import { HttpClient, HttpErrorResponse, HttpParams } from "@angular/common/http";

Next, update the sendGetRequest() method as follows:

  public sendGetRequest(){
// Add safe, URL encoded_page parameter
const options = { params: new HttpParams({fromString: "_page=1&_limit=20"}) };
return this.httpClient.get(this.REST_API_SERVER, options).pipe(retry(3), catchError(this.handleError));
}

We used HttpParams and fromString to create HTTP query parameters from the _page=1&_limit=20 string. This tells to returns the first page of 20 products.

Now the sendGetRequest() will be used to retrieve the first page of data. The received HTTP response will contain a Link header with information about the first, previous, next and last links of data pages.

In the Link header you’ll get first, prev, next and last links. In the next step, we'll see how to extract these pagination links by parsing full HTTP responses.