Angular is a complete platform for creating client side applications so, we don't need any other external libraries for doing common operations like Http requests. Angular provides the HttpClientModule, which allows us to send Http requests and make API calls to remote Http servers. HttpClient is available from the package @angular/common/http.
Modern web browsers has two standard APIs for sending Http requests i.e. XMLHttpRequest interface and the fetch(). The HttpClientModule is built on top of the XMLHttpRequest interface. HttpClientModule wraps all the complexities of XMLHttpRequest interface and provides extra features such as:-
To establish communication between front-end and back-end we can use HttpClient, and to use this module just follow the below steps:-
To use HttpClient, first we neet to import it from @angular/common/http in the main root module.
import { HttpClientModule } from '@angular/common/http';
Now, add HttpClientModule module to the imports array of the main root module.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [ ],
imports: [
BrowserModule,
HttpClientModule
],
providers: [ ],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Now, having imported HttpClientModule into the main root module, you can inject the HttpClient into any where in the application class.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppService {
constructor(private http: HttpClient) { }
}
this.http.get('getUrl');
this.http.post('postUrl', postData);
this.http.put('putUrl', value);
this.http.patch('patchUrl', value);
this.http.delete('deleteUrl', { responseType: 'text' });
Http Interception is a one of the major feature of @angular/common/http package introduced in Angular version 4.3. With interception, we can declare interceptors that inspect and transform HTTP requests/responses between our application and the server.
To implement a Http Interceptor, first we have to declare a class that implements the intercept() method of the HttpInterceptor interface.
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AppInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
return next.handle(req);
}
}