H1 — Angular HTTP in Depth : Fetch-Data, Send-Data, Handle-Http-Error

Sourabhh Sethii
DXSYS
Published in
4 min readMay 25, 2020

Let us start with new article series Angular HTTP in Depth. Here we will be looking Http in detail such as fetching data, sending data, handle http errors, failed request, set http request, read custom http headers, fetch non json data, applying http checking, listen to progress events, interceptor and mocking http request etc.

We will look below topics in this article.

1.) Fetch data from an API using the HttpClient

2.) Send data via HTTP

3.) Handling HTTP Error.

Angular-HTTP-In-Depth

Create Project — You can create angular project or to know more about it, you can check the Angular Article Series. Click Here.

Create Component — To know more about it. Click Here.

Create Services — To know more about it. Click Here.

Repository For this Article Series Available at below location

Click Here Redirect to GitHub Repository.

So I have here a very simple application.You can clone above repository on you machine and run the application.

Fetch data from an API using the HttpClient

From > 4.3.1 angular/common library , HttpClientModule is available.

Step 1.) import HttpClientModule

Import this module in import array of the AppModule as shown below.

import {HttpClientModule} from ‘@angular/common/http’;
imports: [ BrowserModule, AppRoutingModule, HttpClientModule ],

Step 2.) Create a services for Account.

I am taking the example of accounts here so I have create the service for Account. As Shown below e.g. AccountService.

Fetch Account method will be resopsible to get data from ‘/assets/data/account.json’ as shown below. we have used HttpClient as injected in constructor as http private object of HttpClient and used this http object with get method to do a service call to ‘/assets/data/account.json’

‘/assets/data/account.json’ — Mock JSON File available in project folder.

fetchAccount(): Observable<Object> {return this.http.get(‘/assets/data/account.json’);}

Step 3.) Access Account services in AppComponent.

We will create a function to access the fetchAccount Service available in AccountService before that we need to inject AccoutService in constructor accessed by accoutService private object. With this accoutService object we can access and subscribe the functions available in Account Service.

fetchAccount(){this.accoutService.fetchAccount().subscribe((data) => {this.accounts = data;this.message = ‘’;});}

After fetching data, we can give it to account variable , which will be further accessed in template as shown below.

<ul *ngIf=”accouns”><li *ngFor=” let account of accounts”>{{account.Name}} — {{account.Account}}</li></ul>

Finally, we learned how to fetch data and do a simple service call using services.In next section we will look into sending data using POST Request.

Send Data via HTTP

We can do POST request and send the data with HttpClient by accessing POST method as shown below. I have added POST param { ‘name’ : ‘Sourabh’ } and accessing the dummy path ’ /assets/data/account.json?’ .

POST method have two parameters, first will contain the URL path and second will contain the POST Parameter object.

sendAccountDetailsPostParamsHandled(): Observable<Object> {const newAccount = {name: ‘Sourabh’};return this.http.post(‘/assets/data/account.json?’, newAccount);}

Access this services into app component using service object ‘this.accoutService.sendAccountDetailsPostParamsHandled’;

While subscribing service, So when the first parameter here is being invoked in the case of success, the second parameter gets invoked whenever an error happens.

sendDetailsPostParams(){this.accounts = this.accoutService.sendAccountDetailsPostParamsHandled().subscribe((data) => {this.accounts = data;},(error: HttpErrorResponse) => {if (error instanceof Error){this.message = `An error Occured ${error.error.message}`;} else {this.message = `Backend Returend Error code ${error.status}, body was : ${error.message}`;}});}

Handle HTTP Error

We can do handle error handing using HttpErrorResponse. Here we get an HTTP error response which we should here import from the Angular common HTTP package. Then we implement here that callback. Here we can say whenever basically that error is an instance of error, the error object, then this is a client side error.

We obviously want to display something to the user. Let’s say we have a local variable message. Here we basically say, “An error occurred.” We can also include some more information from that error object which we can access here via that error.error object and the message property.

If we open up the network panel here of Chrome, we obviously can see how the requests gets executed to the server, and the server returns us a 404 status code which means not found.

Output Screen

You can click on buttons and open the network window and check the service calls as highlighted in yellow.

Click On Buttons

Conclusion :

We have learned to use HttpClient using HttpClientModule to do HTTP calls to fetch data and send data with error handling.

--

--

Sourabhh Sethii
DXSYS
Editor for

I am an author of Building Digital Experience Platform and I am passionate about emerging technologies. https://sourabhhsethii.com/