Angular HttpClient is a built-in module that helps us to send network requests to any server. Angular HttpClientModule sends GET, POST, PUT, PATCH, and DELETE requests. In addition, Angular can consume REST API using the Angular HttpClient module.
The HttpClient in @angular/standard/Http offers the simplified client HTTP API for Angular applications that rests on an XMLHttpRequest interface exposed by browsers.
Additional benefits of the HttpClient include testability features, typed request and response objects, request and response interception, Observable APIs, and streamlined error handling.
Setup Angular HttpClient
The Angular HttpClient module is already included when creating a new Angular app. We need to register this Angular app. Open and edit `src/app/app.module.ts`, then add this import of HttpClientModule that is part of @angular/common/http.
Before using a HttpClient, you need to import an Angular HttpClientModule. Most apps do import in the root AppModule.
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ BrowserModule, // import HttpClientModule after BrowserModule. HttpClientModule, ], declarations: [ AppComponent, ], bootstrap: [ AppComponent ] }) export class AppModule {}
The Angular HttpClient can use or inject with the Angular service or component.
Setup Angular Service File
In an Angular application, creating a service file related to a particular angular module is best.
If an angular app needs to interact with the backend server, we can write the API calling code inside the service file.
So, if we need to send a POST request to the server, we import the HttpClient inside the service file and make an AJAX request to the server with the data object. After a successful request, the server responds to the client.
Create a service file by the following command.
ng g s config
Write the following code inside the config.service.ts file.
// config.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ConfigService { constructor(private http: HttpClient) { } }
Create a backend Server
We need the fake data to work with, so I am using one package called json-server for this tutorial. Okay, so let us install the package using the Yarn package manager.
yarn global add json-server
# or
npm install -g json-server
We need to create the folder inside the src directory called data, and in that folder, create one file called db.json. Let us add the following data inside the db.json file.
{ "characters": [ { "id": "1", "name": "Peter Dinklage", "age": "45" }, { "id": "2", "name": "Lina Heady", "age": "43" }, { "id": "3", "name": "Emilia Clarke", "age": "30" }, { "id": "4", "name": "Kit Harrington", "age": "30" }, { "id": "5", "name": "Sean Bean", "age": "50" }] }
Start the JSON server using the following command.
json-server --watch src/data/db.json --port 4000
Our JSON server is started at port: 4000, and the URL is http://localhost:4000/characters.
Angular HttpClient GET request.
Write the following code inside the config.service.ts file.
// config.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class ConfigService { constructor(private http: HttpClient) { } url = 'http://localhost:4000'; getCharacters() { return this .http .get(`${this.url}/characters`); } }
The HttpClient.get() method parsed a JSON server response into an anonymous Object type. It doesn’t know what the shape or attributes of that object are.
You can tell the HttpClient the type of response to make consuming the output easier and more prominent.
First, define the interface with the Characters attribute.
export interface Characters { id: Number; name: String; age: Number; }
Then, specify that interface as an HttpClient.get() call’s type parameter in the service.
Angular HttpClient Error Handling
We have to add an error handling to handle any error on every HttpClient request. Write the following code inside the config.service.ts file.
private handleError(operation = 'operation', result?: T) { return (error: any): Observable => { console.error(error); this.log(`${operation} failed: ${error.message}`); return of(result as T); }; } private log(message: string) { console.log(message); }
We create two functions for handling and printing error logs in the above codes.
There are the new required modules, so add them to existing imports.
import { Observable, of } from 'rxjs';
Add a HttpClient request function with catchError.
getCharacters() { return this.http.get(`${this.url}/characters`).pipe( catchError(this.handleError<Characters[]>('characters', []))); }
Angular HTTP Headers
To add the custom HTTP Headers in our HTTP request, then, in addition to the headers, the browser already attaches automatically. We can do this by using the HttpHeaders class.
const headers = new HttpHeaders() .set("X-CustomHeader", "custom header value"); getCharacters() { return this .http .get(`${this.url}/characters`, {headers}); }
As we can see, HttpHeaders also has an immutable API, and we are passing a configuration object as the second argument of the get() call.
This configuration object only has one header property, just like the defined local const. So we used the object short-hand creation notation to describe the configuration object.
Angular PUT request
Like in GET requests, we can also use the Angular HTTP Client to do all the other available HTTP methods, namely the methods typically used for data modification, such as PUT.
The PUT method should only be used if we want to replace the value of the resource.
Angular PATCH request
Most often than not, instead of providing a completely new version of the resource, we want to update a single property. And this is the primary use case for using the HTTP PATCH method.
The PATCH request is helpful when there is some further server-side modification of the patched values, such as via a database trigger or a Firebase rule.
Angular HttpClient DELETE request
Another frequent operation we want to do is trigger the logical deletion of some data. This operation can completely wipe the data from our database or mark some data as deleted.
Angular HttpClient POST request in Angular
If the operation we are trying to do does not fit the description of any of the methods above (GET, PUT, PATCH, DELETE), then we can use an HTTP wildcard modification operation: POST.
That operation typically adds new data to the database, although many other use cases exist.
That’s it.
Michael
Great until you get down to config.service.ts then each section of code is missing what file it should go in. Could you update this to explicitly say where each block of code goes?