Angular HttpClient- GET, POST, PUT and DELETE requests

Why HttpClient?

We need to use HttpClient to communicate with our back-end HTTP server or a third-party server that has CORS enabled.

We are going to cover:-

  • Setup the HttpClientModule,
  • Send a GET request with HttpClient.get(),
  • Send a POST request with HttpClient.post(),
  • Send a PUT request with HttpClient.put(),
  • Send a DELETE request with HttpClient.delete()

HttpClient module which is an improved version of the Http. The old API is still available in @angular/http in Angular 6

import HttpClientModule from @angular/common/http

 

Importing HttpClientModule in the root

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

 

Now ready to use the new HttpClient API to send GET, POST, PUT and DELETE requests in our application.

Create an Angular Service which will interact with back end services

Open command prompt in the root folder of your project and run below command.

ng generate service service-name 
//replace service-name according to your requirement. Here we are using globalhttp.

 

It will generate bellow files

src/app/ globalhttp.service.spec.ts (for tests)
src/app/ globalhttp.service.ts

 

Creating Angular Components (c=component)

ng g c customerlist
ng g c customerdetails
ng g c customercreate
ng g c customerupdate

 

import all your components in the app module.

import { CustomerlistComponent } 
    from './customerlist/customerlist.component';
import { CustomerdetailsComponent } 
    from './customerdetails/customerdetails.component';
import { CustomercreateComponent } 
    from './customercreate/customercreate.component';
import { CustomerupdateComponent } 
    from './customerupdate/customerupdate.component';

 

To use all API call in your component file you need to import a service file in your app module.

import { GlobalService } from './services/global.service';

 

In globalhttp.service.ts file import all dependencies which are required for HTTP calls.

import { HttpClient, HttpHeaders, HttpErrorResponse } 
   from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';

 

Put all your config details in an environment file like apiurl, key, etc.

endpoint = environment.apiurl 
//e.g https://www.randomuser.me/

 

Create a header parameter for the HTTP calls.

httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

 

Generate http alias for HTTP calls.

constructor(private http: HttpClient) {  }

 

create a function to extract all response data.

private extractData(res: Response) {
    let body = res;
    return body || {};
  }

 

Now we are creating API calls here.

GET method to fetch all customer lists.

getCustomerList(): Observable<any> {
    return this.http.get(this.endpoint + 'getCustomerList').pipe(
      map(this.extractData));
  }

POST method to send data to the server.

createCustomer (data): Observable<any> {
    return this.http.post<any>(this.endpoint + ' createCustomer ' ,
      JSON.stringify(data), this.httpOptions)
   .pipe(
      map(this.extractData)
    );
  }

 

PUT method to update customer data:

updateCustomer(id, data): Observable<Employee> {
return this.http.put<Employee>( this.endpoint + '/ updateCustomer /' + id,
    JSON.stringify(data), this.httpOptions)
.pipe(
map(this.extractData)
);
}

DELETE method to delete customer:

deleteCustomer(id){
return this.http.delete<Employee>(this. endpoint + '/ deleteCustomer /' + id,
 this.httpOptions)
.pipe(map(this.extractData))
}

 

In your component file if you want to use those services you need to subscribe to those API functions.

import { GlobalhttpService } from ‘./globalhttp.service’;

Before that import your globalhttp.service.ts file in the app module and add GlobalhttpService in providers.

@NgModule({
    imports: [ ],
    providers: [
        GlobalhttpService
    ],
    declarations: [ ],
    exports: []
})

 

After adding to the root module, import service.ts into a component so you can access all API calls.

import { GlobalhttpService } from './globalhttp.service';
constructor(private rest: GlobalhttpService) { }
this.rest. getCustomerList ().subscribe((result) => {

console.log(result)

}, (err) => {

console.log(err);

});

 

Note:- You can use the same code to call all other API just need to pass data parameters as per requirements.

That’s it. Hopes this will help you to create your HttpClient flow for your application. Let me know if there any change required.

Leave a Reply

Your email address will not be published. Required fields are marked *