HttpClient API in Angular

Vignesh Ravichandran

--

Heading image

HttpClient is used to handle Http request/response, to and from a backend api. It can be found under angular/common/http

Steps to import and use:

In order to use the Http client, we have to first import the HttpClientModule to our app.module.ts
Then we can create our own services using the Httpclient along with dependency injection of angular

example:

app.service.ts is my file and to do the dependency injection,I have to include Httpclient in my constructor

constructor(private http: HttpClient) { }

point to note:
declaring as private while dependency injection is preferred rather than declaring them as public

after completing the setup, It is time to see how we can use the HttpClient for various operations

GET

Inside our service file we can use get method from our httpClient class like this

this.http.get<users[]>(this.apiUrl + ‘getUserData’)
where apiUrl could be your backend url

We can define the headers, type of return, response type, params to be passed in our GET request itself

example:

options for GET

A scenario where I wanted to receive data as text but when the syntax didn’t allowed me

responseType: 'text'

throws an error stating that it cannot accept text in place of json

A workaround is to use the following syntax for the response type to be received as text

responseType: 'text' as 'json',

These are the options available to be passed in the Get request and this is how we can use this.
for further drilldown in this topic., please refer to the api page

POST/PUT

The Post and Put request with HTTP client are very similar in nature. We have to pass the request body as a parameter in the method call

example:

this.http.post<userdata[]>(this.apiUrl + ‘saveUser’, savedata)
here savadata refers to the data that needs to be saved in the database

DELETE

The delete is also simple in our httpclient, We can pass either the id that needs to be deleted or an object depending on our API

example:

this.http.delete<void>(this.apiUrl + ‘deleteUser’,userId)
here userId refers to the data that needs to be deleted from the database

points to be noted:

In order to send the requestOptions in the post, put, delete. We can do it in the same way as the Get request. We have to put the options needed as the third parameter

We have to mandatorily subscribe to any http calls we are making. Since these are returning Observables and in order to execute the operation, We have to subscribe them

For more information on this, refer to

https://angular.io/guide/http#making-a-delete-request

Sign up to discover human stories that deepen your understanding of the world.

--

--

Vignesh Ravichandran
Vignesh Ravichandran

Written by Vignesh Ravichandran

Software Development Engineer with skills in Problem solving, Java Programming, Angular, Spring boot, Docker, Podman. www.youtube.com/@vigneshravichandran3096

No responses yet

Write a response