Getting Started With The Angular HTTP Client -- Words (1193)

Angular
How to use HttpClient to make HTTP Requests in Angular 4+

Throughout this post, we are going to see a practical guide for the new Angular Http Client module.

This tutorial is intended for the new Http Client module, available starting from Angular version 4, at @angular/common/http.

We'll see examples of common HTTP methods such as GET, PUT, PATCH, POST and DELETE, that you usually need to use when communicating with a Restful API server.

Introducing HttpClient Module

Angular 4.3.0-rc.0 shipped with an improved version of Http Client API which lives at @angular/common/http. But also the old API is still available at @angular/http for easing the migration process of existing Angular 2 applications.

Now lets see how to actually use HttpClient:

Setting up the HttpClient Module

Before you can use the new HTTP Client module, you must add it to imports array in our app module:

So start by importing the root module, HttpClientModule from @angular/common/http:

import { HttpClientModule } from '@angular/common/http';

Then add it to imports array:

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

After adding the root module to app imports, we are now ready to use the new HTTP Client API.

What are we going to query ?

For the sake of this tutorial, we are going to create a two-seconds API server, which exposes a fake API endpoints, using json-server:

First you should install json-server via npm:

npm install -g json-server 

Next you need to create a JSON file, which will act as a database of our server, then run the server:

As an example add these data to db.json

{
    "customers": [
        {
        "id": 1,
        "name": "Customer001",
        "email": "[email protected]",
        "tel": "0526252525"
        },
        {
        "id": 2,
        "name": "Customer002",
        "email": "[email protected]",
        "tel": "0527252525"
        },
        {
        "id": 3,
        "name": "Customer003",
        "email": "[email protected]",
        "tel": "0528252525"
        }

    ]
}

Then run:

json-server --watch db.json 

You can now make queries just like any Rest service.

You can find more information of what you can do with json-server from this link.

Example of Making HTTP GET Requests using HttpClient

Lets display the list of customers using the HttpClient module in a sample component

First lets see the required steps:

  1. Import HttpClient from @angular/common/http
  2. Inject HttpClient via component constructor
  3. Make HTTP GET Requests using .get(endpoint) method
  4. Subscribe to the returned observable and show results

Here is the source code of our example:

import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { HttpClient } from "@angular/common/http";


class Customer {
    id : number;
    name: string;
    email: string;
    tel: string;
}

@Component({
selector: 'customers',
template: `
    <ul *ngIf="customersObservable | async as customers else empty">
        <li *ngFor="let customer of customers">

        </li> 
    </ul>
    <ng-template #empty> No Customers Yet </ng-template>
`})
export class CustomerComponent implements OnInit {
    customersObservable : Observable<Customer[]>;

    constructor(private httpClient:HttpClient) {
    }

    ngOnInit() {
        this.customersObservable = this.httpClient
            .get<Customer[]>("127.0.0.1:3000/customers")
            .do(console.log);
    }
}

HTTP GET Request Parameters : HttpParams

In many use cases, we need to feed some parameters to the API endpoint we are querying, for example for pagination or for ordering data etc.

So lets take an example:

Lets say that we need to make a GET request to this URL:

http://127.0.0.1:3000/customers?_page=1&_limit=1

To get the first two customers of the first page.

First we need to import HttpParams class

import {HttpParams} from "@angular/common/http";

Next we construct an HttpParams object:

const params = new HttpParams().set('_page', "1").set('_limit', "1");

Then we call .get() method with these parameters, then assign the returned Observable to customersObservable:

this.customersObservable = this.httpClient.get("http://127.0.0.1:3000/customers", {params});

Using fromString to easilly create HttpParams

We can also build HTTP parameters directly from a query string, for example in our previous example:

http://127.0.0.1:3000/customers?_page=1&_limit=1

The query string:

    _page=1&_limit=1

So we can simply do:

const params = new HttpParams({fromString: '_page=1&_limit=1'});

Generic API request() method

We have seen how to use the .get() method to make HTTP GET requests, now we'll see a generic method to make GET and other HTTP methods (POST, PUT etc.).

Using .request() we can rewrite the previous example:

const params = new HttpParams({fromString: '_page=1&_limit=1'});

this.customersObservable = this.http
    .request("GET","http://127.0.0.1:3000/customers", 
        {
            responseType:"json",
            params
    });

Adding custom HTTP Headers to requests

We can also add custom HTTP headers to our HTTP requests using HttpHeaders class.

Lets see an example:

First create an instance of HttpHeaders class and set your custom HTTP header:

const headers = new HttpHeaders().set("X-CustomHttpHeader", "CUSTOM_VALUE");

Next send the GET request:

this.customersObservable = this.httpClient.get("http://127.0.0.1:3000/customers", {headers});

Sending HTTP PUT Requests

HTTP PUT method is used to completely replace a resource on the API server. We can use HttpClient to send a PUT request to an API server using the .put() method, for example:

this.httpClient.put("http://127.0.0.1:3000/customers/1",
    {
        "name": "NewCustomer001",
        "email": "[email protected]",
        "tel": "0000252525"
    })
    .subscribe(
        data => {
            console.log("PUT Request is successful ", data);
        },
        error => {
            console.log("Rrror", error);
        }
    );  

Sending HTTP PATCH Requests

HTTP PATCH is used to update a resource on the server. HttpClient provides a .patch():

this.httpClient.patch("http://127.0.0.1:3000/customers/1",
    {
        "email": "[email protected]"
    })
    .subscribe(
        data => {
            console.log("PUT Request is successful ", data);
        },
        error => {
            console.log("Error", error);
        }
    );  

Sending HTTP DELETE Requests

Now lets see how we can send a DELETE request to delete a resource from the API server. HttpClient provides the .delete() method for this matter:

this.httpClient.patch("http://127.0.0.1:3000/customers/1")
    .subscribe(
        data => {
            console.log("PATCH Request is successful ", data);
        },
        error => {
            console.log("Error", error);
        }
    );          

Sending HTTP POST Requests

An HTTP POST method has many uses but the most use case is when we need to add new data on the server so lets take an example of adding a new customer to our Rest API server database:

this.httpClient.post("http://127.0.0.1:3000/customers",
    {
        "name": "Customer004",
        "email": "[email protected]",
        "tel": "0000252525"
    })
    .subscribe(
        data => {
            console.log("POST Request is successful ", data);
        },
        error => {
            console.log("Error", error);
        }
    );           

Conclusion

So we have seen how to interact with a Restful API server using common HTTP methods i.e GET, PUT, PATCH, DELETE and POST.

For the sake of testing we have used a fake Rest api server but you can use the same examples with a real backend server.




mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.