a blog for those who code

Tuesday 7 May 2019

Knowing About HttpClient and How to use it in Angular


One of the aspect of Web Application is to communicate with the backend services (API) through HTTP. HttpClient module of Angular allows developers to send HTTP requests which is available from @angular/common/http package.

As you might know that most of the browsers support two different APIs for making HTTP requests and those are XMLHttpRequest and fetch() API. The HttpClient module is built on the XMLHttpRequest intaerface.

Some of the interesting features of HttpClient's are :

1. JSON data returned by default, so that we do not have to parse it using response.json().
2. Interceptors in HttpClient allows us to intercept or mutate HTTP requests and responses. Note that in HttpClient, request and response objects are immutable, so you need to create a copy of those objects before modifying.
3. Upload and Download progress events in HttpClient is helpful for capturing progress of your upload/download feature.

Why Pipes are Useful in Angular and How to Create Custom Pipes


Setup HttpClient


For setting up the HttpClient you will need to import the HttpClientModule from @angular/common/http and then add it to @NgModule.imports array as shown below :

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

@NgModule({
  declarations: [
  ],
  imports: [
     ...,      
     HttpClientModule,
     ...
  ], 
  providers: [
  ]
})

export class AppModule { }

Basic Usage


Making GET, POST, PUT, etc requests is very easy and you will always get JSON response by default. A typical GET request looks like :


constructor(private http: HttpClient) {}

myGetRequest() {
  this.http.get(this.url).subscribe(res => {
    // res is the JSON Response from the API url
  });
}

Since the get method of HttpClient returns an Observable, we need to subscibe to it. Alternatively you can also specify the interface of the response and type-check against it

export interface MyInterface {
}

constructor(private http: HttpClient) {}

myGetRequest() {
  this.http.get<MyInterface>(this.url).subscribe(res => {
    // res is the JSON Response from the API url
  });
}

When to use [routerLink] or routerLink in Angular


The response object does not return the full data, it only returns the body of the response. To get the full response object you need to pass observe key with a value of 'response' to get full response as shown below :

myGetRequest() {
  this.http.get<MyInterface>(this.url, {observer: 'response'}).subscribe(res => {
    // res is the JSON Response from the API url
  });
}

To get the error object you need to add a second callback to the .subscribe method as shown below :

myGetRequest() {
  this.http.get<MyInterface>(this.url, {observer: 'response'}).subscribe(
    res => {
      // res is the JSON Response from the API url
    },
    (error: HttpErrorResponse) => {
      // check the error here
    });
}

Till now we have seen the GET request, now lets see the other type of HTTP requests. Let us first create a simple object which contains the values to be passed to the server:

let myOptions : any = {
  observe: "response",
  headers: new HttpHeaders({
    "Content-Type": "application/json",
  })
};

Then we will be making a POST request like below:

myPostRequest() {
  this.http.post<MyInterface>(this.url, bodyContent, myOptions)
    .subscribe(...);
}

Similarly we have a PUT and DELETE request.

Understanding Dependency Injection in Angular


What is HTTP Interceptors


As discussed above Interceptors in HttpClient allows us to intercept or mutate HTTP requests and responses, that means we will get access to request headers and body before it is sent to th backend and thus it enables us to transform the request before sending it to the server. Similarly the response object can be transformed before using it in the application.

Creating HTTP Interceptor is easy, where you will create an injectable service and implement an HttpInterceptor interface. A simple interceptor looks like below:

export class MyInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Intercept the request
    return next.handle(req);
  }
}

We also need to modify the App Module to include our Interceptor in the providers array as shown below :

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './MyInterceptor'

providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: MyInterceptor,
    multi: true
  }
]

Thus after the above step your interceptor will be used for every request. So let's say you want to add an authorization for every request, you can add it in the interceptor as shown below, where we are setting the 'auth' params with every request:

export class MyInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      params: req.params.set('auth', this.authService.myToken())
    });
    return next.handle(req);
  }
}

Progress Events


One of the feature of HttpClient is to track the progress of a request, it can be both for Uploading as well as Downloading a file. To receive the progress we need to set the 'reportProgress' property of the options to true. Then we can track it using the event type DownloadProgress and Upload Progress as shown below :

myPostRequest() {
  const req = new HttpRequest('POST', this.url, file, {
    reportProgress: true
  })
  this.httpClient.request(req).subscribe(e => {
    if(e.type === HttpEventType.DownloadProgress) {
      // check percentage donwload
    } else {
      // Download Complete
    }
  })
}

Career Category (English)728x90

No comments:

Post a Comment