Angular 10 HttpClient Headers and Typed/Full Responses: Pagination Example

Angular 10 HttpClient Headers and Typed/Full Responses: Pagination Example

In this post we will give you information about Angular 10 HttpClient Headers and Typed/Full Responses: Pagination Example. Hear we will give you detail about Angular 10 HttpClient Headers and Typed/Full Responses: Pagination ExampleAnd how to use it also give you demo for it if it is necessary.

In this Angular 10 HttpClient tutorial, we’ll see how you can get headers and the full response when sending Http requests with HttpClient and how to use typed responses.

We’ll see an example of getting paginated data from our API server by using the Link header. We’ll see how to retrieve the full response and how to get an HTTP header from the response.

Wikipedia defines the Link header as:

The Link: header in HTTP allows the server to point an interested client to another resource containing metadata about the requested resource.

How to Get Headers and Full Responses with HttpClient in Angular 10?

We’ll only build the Angular service of our example pagination demo so you should know how to create a project and other artifacts like Angular components. Otherwise, you can follow the other tutorials in our website that show how to get started with Angular.

How to Obtain the Full Http Response

You can obtain the full response using the observe property and specifying the response value. This way Angular will hand you the full HttpResponse object.

Let’s see this with an example.

In your Angular 10/8 project, run the following command to generate a new model:

$ ng generate class contact

Open the src/app/contact.ts file and add the following code:

exportclassContact{id:number;firstName:string;lastName:string;email:string;phone:string;city:string;country:string;title:string}

Next, run the following command to generate a new Angular service:

$ ng generate service api

Open the src/app/api.service.ts file and add the following code:

import{Injectable}from'@angular/core';import{HttpClient}from'@angular/common/http';@Injectable({providedIn:'root'})exportclassApiService{apiURL:string='http://localhost:3000';publicfirst:string="";publicprev:string="";publicnext:string="";publiclast:string="";constructor(privatehttpClient:HttpClient){}}

We simply import HttpClient from the @angular/common/http package and inject is as httpClient via the service constructor.

We declare the apiURL variable that contains the URL of the API server from where we need to fetch data.

Finally, we add the first, prev, next and last variables which will hold the links for the first, previous, next and last pages of data.

Note: We assume that our API server uses the Link header for sending pagination information to the clients.

Next, import the Contact model and tap() operator in your service:

import{Contact}from'./contact';import{tap}from'rxjs/operators';

Next, add the following CRUD methods:

publiccreateContact(contact:Contact){returnthis.httpClient.post('${this.apiURL}/contacts/',contact);}publicupdateContact(contact:Contact){returnthis.httpClient.put('${this.apiURL}/contacts/${contact.id}',contact);}publicdeleteContact(id:number){returnthis.httpClient.delete('${this.apiURL}/contacts/${id}');}

We use Angular HttpClient to send POST, PUT and DELETE request to our API server.

Getting the Full Http Response in Angular 10

Now, let’s see how to retrieve the full HTTP response with pagination information from the API server.

In your service, add the following method to get a list of paginated contacts:

publicgetFirstPage(){returnthis.httpClient.get<Contact[]>('${this.apiURL}/contacts?_page=1',{ observe: 'response' }).pipe(tap(res => {constLink=this.parse_link_header(res.headers.get('Link'));this.first=Link["first"];this.last=Link["last"];this.prev=Link["prev"];this.next=Link["next"];}));}

We use HttpClient to send a GET request to our API server to retrieve the first page of data. The get() method takes the URL of API endpoint as a first parameter and an options object as the second parameter. In the options object, we add the observe property with a response value to instruct Angular to provide us with the full HTTP response. This way we can get and parse the Link header containing pagination information sent from our API server.

We use the pipe() method and the tap() operator to run a side effect code that retrieves the Link header from the res.headers map, parse it and assigns the values to their respective variables.

Note: Here we assume that the first page of data is accessed from the so you should change that with any other format used by your API server.

You also need to add the parse_link_header() method which parses the Link header and returns an array with the first, previous, next and last links of data pages:

parse_link_header(header){if(header.length==){return;}letparts=header.split(',');varlinks={};parts.forEach(p=>{letsection=p.split(';');varurl=section[].replace(/<(.*)>/,'$1').trim();varname=section[1].replace(/rel="(.*)"/,'$1').trim();links[name]=url;});returnlinks;}

You also need a second method that fetches specified pages of data. An example implementation looks like:

publicgetNextPage(url:string){returnthis.httpClient.get<Contact[]>(url,{observe:'response'}).pipe(tap(res=>{constLink=this.parse_link_header(res.headers.get('Link'));this.first=Link["first"];this.last=Link["last"];this.prev=Link["prev"];this.next=Link["next"];}));}

It has the same implementation of the previous method except that we provide the URL for the page to retrieve as a parameter to the method.

Conclusion

In this quick tutorial, you have seen how you can use typed and full Http responses in Angular 10 and how to retrieve headers in HttpClient to create a pagination service that retrieves pages of data from a server.


Hope this code and post will helped you for implement Angular 10 HttpClient Headers and Typed/Full Responses: Pagination Example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US