top of page
Search
  • Writer's picturesourabhh sethii

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

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.


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



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 { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {HttpClientModulefrom '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AccoutService } from './account.service';

@NgModule({
 declarations: [
 AppComponent
  ],
 imports: [
 BrowserModule,
 AppRoutingModule,
 HttpClientModule
  ],
 providers: [AccoutService],
 bootstrap: [AppComponent]
})
export class AppModule { }


 

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.


import { AccoutService } from './account.service';
import { Component } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'Angular-Http-In-Depth';
 accounts = null;
 message = '';
 constructor(private accoutServiceAccoutService){

  }

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

 sendDetails(){
 this.accounts = this.accoutService.sendAccountDetails()
    .subscribe((data=> {
 this.accounts = data;
 this.message = '';
     }
     );
  }

 sendDetailsQueryParams(){
 this.accounts = this.accoutService.sendAccountDetailsQueryParams()
    .subscribe((data=> {
 this.accounts = data;
 this.message = '';
     }
     );
  }

 sendDetailsPostParams(){
 this.accounts = this.accoutService.sendAccountDetailsPostParamsHandled()
    .subscribe((data=> {
 this.accounts = data;
     },
     (errorHttpErrorResponse=> {

 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}`;
      }

     }
     );
  }
}



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.



import { Injectable } from '@angular/core';
import { HttpClientHttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AccoutService {

 constructor(private httpHttpClient) {

    }

 // tslint:disable-next-line: ban-types
 fetchAccount(): Observable<Object> {
 return this.http.get('/assets/data/account.json');
    }

 // tslint:disable-next-line: ban-types
 sendAccountDetails(): Observable<Object> {
 return this.http.get('/assets/data/account.json?queryparamTest=123');
    }
 // Get Request Handled
 // tslint:disable-next-line: ban-types
 sendAccountDetailsQueryParams(): Observable<Object> {
 return this.http
            .get('/assets/data/account.json?', {
 params: new HttpParams().set('id''123')
            });
    }
 // tslint:disable-next-line: ban-types
 sendAccountDetailsPostParamsHandled(): Observable<Object> {

 const newAccount = {
 name: 'Sourabh'
        };
 return this.http
            .post('/assets/data/account.json?'newAccount);
    }
}


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.








Conclusion :

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


19 views0 comments

Recent Posts

See All

Angular : Lazy-loading-ngmodules

By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules loads. Lazy loading—a design...

コメント


Post: Blog2_Post
bottom of page