HttpClient In Angular

HttpClient In Angular

In this article, We will learn how to use HttpClient to make HTTP queries like GET and POST to the backend server. In Angular 4.3, the Angular HTTP client module is introduced. This new API may be found in the @angular/common/http package. It takes the place of the previous HttpModule. The HTTP Client takes use of the RxJs Observables. The HttpClient's response is observable, thus it must be subscribed to. All of this will be covered in this article.

Using Angular HttpClient

In Angular, the HttpClient is a separate model that can be found in the @angular/common/http package. The steps below demonstrate how to use the HttpClient in an Angular app.

Import HttpClient Module in Root Module

It must be imported into our main module, app.module. We must also include it in the imports metadata array.

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
 
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Import Required Module in Component/Service

Then, in the component or service, import HttpClient from @angular/common/http.

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

Inject HttpClient service

In the constructor, inject the HttpClient service.

constructor(public http: HttpClient) {
}

Call the HttpClient.Get method

Use HttpClient.Get a method to send an HTTP request. When we Subscribe to the get() method, the request is sent. When the response comes in, map it to the desired object and show the outcome.

public getData() {
  this.HttpClient.get<any>(this.baseUrl+'users/'+this.userName+'/repos')
           .subscribe(data =&gt; {
               this.repos= data;
           },
           error =&gt; {
           }
  );
}

What is Observable?

Observable is used by the Angular HTTPClient. As a result, it's critical to grasp the fundamentals.

We can use observable to manage async data. Observables can be thought of as a collection of items that arrive asynchronously over time.

The observer design pattern is implemented by the observables, which keep a list of dependents. Observers are what we term these dependents. Any state changes are automatically notified by the observable, which is usually called one of their methods.

An Observable is subscribed to by an Observer. When the value of the Observable changes, the observer reacts. An Observable can have numerous subscribers, and when the state of the Observable changes, all of the subscribers are notified.

When an Observer subscribes to an observable, the three callbacks must be passed (optionally). complete(), next(), and error() (). When the observable receives a value, it calls the next() function. The complete() callback is invoked when the observable completes. When an error occurs, the error() callback is invoked with the specifics of the error, and the subscriber is terminated.

Angular makes considerable use of Observables. Observables are used throughout the new HTTPClient Module and Event system.

The Observables are a feature that has been proposed for the next edition of Javascript. To implement Observables, Angular employs a third-party library called Reactive Extensions or RxJs. These RxJx courses will teach you all you need to know about RxJs.

Observables Operators

Methods that act on an Observable and return a new Observable are known as operators. Each Operator alters the value that it is given. In a chain, these operators are applied one after the other.

RxJs have a number of Operators that can be used to filter, select, transform, combine, and compose Observables. Map, filter, take, combine, and other operators are examples of operators.

How to use RxJs

The RxJs library is quite extensive. As a result, Angular exposes a simplified version of Observables. You can use the following import statement to import it.

import { Observable } from 'rxjs';

Only the features that are required are imported in the above import. None of the Operators are included.

You must import observables operators in order to use them. The map and catchError operators are imported in the following code.

import { map, catchError } from 'rxjs/operators';

HTTP GET

The HttpClient.get method sends an HTTP Get Request to an API endpoint and converts the response to the required type. The body of the response is parsed as JSON by default. If you desire a different kind, use the observe & responseType options to define it directly.

Syntax

get(url: string, 
     options: {
         headers?: HttpHeaders | { [header: string]: string | string[]; };
         params?: HttpParams | { [param: string]: string | string[]; };
         observe?: "body|events|response|";
         responseType: "arraybuffer|json|blob|text";
         reportProgress?: boolean; 
         withCredentials?: boolean;}
    ): Observable<>

Options

We have numerous configuration choices under options that we can use to configure the request.

headers It enables you to include HTTP headers in incoming requests.

observe The HttpClient.get method returns the JSON-parsed body of the response (or type specified by the responseType). You may need to read the full response, including the headers and status codes, at times. Set the observe attribute to the response to accomplish this.

The possibilities are as follows:
  • a response that sends the complete response back to the sender
  • a body that merely returns the body
  • events that return the response in the form of events

params Allow us to add URL parameters or Get Parameters to the Get Request.

reportProgress This property is boolean. If you want to be updated about the progress of the Get Request, set this to true. When you have a huge quantity of data to download (or upload) and want the user to be notified of the progress, this is a very handy feature.

responseType The default response type is JSON. This argument should be used if you want a different type of response. arraybuffer, blob, JSON, and text are all allowed options.

withCredentials It's a boolean value. HttpClient.get will request data with credentials if the value is true (cookies)

HTTP Post

The HTTP POST request is sent to the endpoint using HttpClient.post(). To send the request, we must subscribe to the post() method, just as we did with get(). The body of the response was processed as JSON and returned by the post method. This is how things work by default. If you desire a different kind, use the observe & responseType options to define it directly.

The HTTP Post has a similar syntax to the HTTP Get.

post(url: string, 
     body: any, 
     options: { 
        headers?: HttpHeaders | { [header: string]: string | string[]; }; 
        observe?: "body|events|response|"; 
        params?: HttpParams | { [param: string]: string | string[]; }; 
        reportProgress?: boolean; 
        responseType: "arraybuffer|json|blob|text"; 
        withCredentials?: boolean; 
     }
): Observable

An example of an HTTP Post is shown below.

addPerson(person:Person): Observable<any> {
    const headers = { 'content-type': 'application/json'}  
    const body=JSON.stringify(person);
    this.http.post(this.baseURL + 'people', body,{'headers':headers , observe: 'response'})
      .subscribe(
       response=> {
            console.log("POST completed sucessfully. The response received "+response);
        },
        error => {
            console.log("Post failed with the errors");
        },
        () => {
            console.log("Post Completed");
        }
}

HTTP PUT

The HTTP PUT request is sent to the endpoint using HttpClient.put(). The syntax and use of this method are quite similar to that of the HTTP POST method.

put(url: string, 
     body: any, 
     options: { 
        headers?: HttpHeaders | { [header: string]: string | string[]; }; 
        observe?: "body|events|response|"; 
        params?: HttpParams | { [param: string]: string | string[]; }; 
        reportProgress?: boolean; 
        responseType: "arraybuffer|json|blob|text"; 
        withCredentials?: boolean; 
     }
): Observable

HTTP PATCH

The HTTP PATCH request is sent to the endpoint by HttpClient.patch(). The syntax and use of this method are quite similar to that of the HTTP POST method.

patch(url: string, 
     body: any, 
     options: { 
        headers?: HttpHeaders | { [header: string]: string | string[]; }; 
        observe?: "body|events|response|"; 
        params?: HttpParams | { [param: string]: string | string[]; }; 
        reportProgress?: boolean; 
        responseType: "arraybuffer|json|blob|text"; 
        withCredentials?: boolean; 
     }
): Observable

HTTP DELETE

The HTTP DELETE request is sent to the endpoint by HttpClient.delete(). The HTTP GET method's syntax and usage are extremely similar.

delete(url: string, 
      options: {
          headers?: HttpHeaders | { [header: string]: string | string[]; };
          params?: HttpParams | { [param: string]: string | string[]; };
          observe?: "body|events|response|";
          responseType: "arraybuffer|json|blob|text";
          reportProgress?: boolean; 
          withCredentials?: boolean;}
     ): Observable<>

HttpClient Example

Let us develop a HttpClient example app now that we have a basic understanding of the HttpClient model and observables.

Create a new Angular app using the following command:

ng new httpClient

import HttpClientModule

Import the HttpClientModule module as mentioned below in the app,module.ts file. We also include it in the imports list.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now open the app.component.ts file and paste the code below.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
 
export class Repos {
  id: string;
  name: string;
  html_url: string;
  description: string;
}
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
 
  userName: string = "tektutorialshub"
  baseURL: string = "https://api.github.com/";
  repos: Repos[];
 
  
  constructor(private http: HttpClient) {
  }
 
  ngOnInit() {
    this.getRepos()
  }
 
 
  public getRepos() {
 
    return this.http.get<repos>(this.baseURL + 'users/' + this.userName + '/repos')
      .subscribe(
        (response) => {                           //Next callback
          console.log('response received')
          console.log(response);
          this.repos = response; 
        },
        (error) => {                              //Error callback
          console.error('Request failed with error')
          alert(error);
        },
        () => {                                   //Complete callback
          console.log('Request completed')
        })
  }
}

Import HTTPClient

The HTTP Module's HTTPClient is a service that is a key component. It includes methods such as GET, POST, and PUT, among others. We'll have to bring it in.

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

Repository Model

The model that will be used to handle our data.
export class Repos {
  id: string;
  name: string;
  html_url: string;
  description: string;
}

Inject HttpClient

The HttpClient service should be injected into the component. You can read more about Angular dependency injection here.

constructor(private http: HttpClient) {
}

Subscribe to HTTP Get

The GetRepos method calls the HttpClient Service's get() method.

We can cast the returned response object to a type we need using the HttpClient.get method. We take advantage of this capability by specifying the type of the returned result http.get<repos[]>.

An observable is returned by the get() method. As a result, we agree with it.

public getRepos() {
  return this.http.get<repos>(this.baseURL + 'users/' + this.userName + '/repos')
     .subscribe(

We can optionally pass the three callbacks when we subscribe to any observable. complete(), next(), and error(). We just pass two callbacks in this example: next() and error().

Receive the Response

The data is received in the next() callback. Angular reads the body of the response as JSON by default, casts it to an object, and then returns it. As a result, we can use it right away in our app.

(response) => {                           //Next callback
  console.log('response received')
  console.log(response);
  this.repos = response; 
},

Handle the errors

In the error callback, we handle the errors.

(error) => {                              //Error callback
   console.error('Request failed with error')
   alert(error);
 },

Now open the app.component.html file and paste the code below.

<h1 class="heading"><strong>HTTPClient </strong> Example</h1>
 
 
<table class="table">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>HTML Url</th>
      <th>description</th>
    </tr>
  </thead>
  <tbody>
    <tr ngfor="let repo of repos;">
      <td>{{repo.id}}</td>
      <td>{{repo.name}}</td>
      <td>{{repo.html_url}}</td>
      <td>{{repo.description}}</td>
    </tr>
  </tbody>
</table> 
 
<pre>{{repos | json}}</pre>

Conclusion

In this article, we learned how to establish a simple HTTP Service. We also went through the fundamentals of Observables, which aren't often used in Angular.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post