Difference between HttpModule and HttpClientModule
Use the HttpClient
class from HttpClientModule
if you're using Angular 4.3.x and above:
import { HttpClientModule } from '@angular/common/http';@NgModule({ imports: [ BrowserModule, HttpClientModule ], ... class MyService() { constructor(http: HttpClient) {...}
It's an upgraded version of http
from @angular/http
module with the following improvements:
- Interceptors allow middleware logic to be inserted into the pipeline
- Immutable request/response objects
- Progress events for both request upload and response download
You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.
- Typed, synchronous response body access, including support for JSON body types
- JSON is an assumed default and no longer needs to be explicitly parsed
- Post-request verification & flush based testing framework
Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.
Also pay attention that old http was injected using Http
class token instead of the new HttpClient
:
import { HttpModule } from '@angular/http';@NgModule({ imports: [ BrowserModule, HttpModule ], ... class MyService() { constructor(http: Http) {...}
Also, new HttpClient
seem to require tslib
in runtime, so you have to install it npm i tslib
and update system.config.js
if you're using SystemJS
:
map: { ... 'tslib': 'npm:tslib/tslib.js',
And you need to add another mapping if you use SystemJS:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):
- Automatic conversion from JSON to an object
- Response type definition
- Event firing
- Simplified syntax for headers
- Interceptors
I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.
This is a good reference, it helped me switch my http
requests to httpClient
.
It compares the two in terms of differences and gives code examples.
This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :
Importing
import {HttpModule} from '@angular/http';import {HttpClientModule} from '@angular/common/http';
Requesting and parsing response:
@angular/http
this.http.get(url) // Extract the data in HTTP Response (parsing) .map((response: Response) => response.json() as GithubUser) .subscribe((data: GithubUser) => { // Display the result console.log('TJ user data', data); });
@angular/common/http
this.http.get(url) .subscribe((data: GithubUser) => { // Data extraction from the HTTP response is already done // Display the result console.log('TJ user data', data); });
Note: You no longer have to extract the returned data explicitly; by default, if the data you get back is type of JSON, then you don't have to do anything extra.
But, if you need to parse any other type of response like text or blob, then make sure you add the responseType
in the request. Like so:
Making the GET HTTP request with responseType
option:
this.http.get(url, {responseType: 'blob'}) .subscribe((data) => { // Data extraction from the HTTP response is already done // Display the result console.log('TJ user data', data); });
Adding Interceptor
I also used interceptors for adding the token for my authorization to every request, reference.
like so:
@Injectable()export class MyFirstInterceptor implements HttpInterceptor { constructor(private currentUserService: CurrentUserService) { } intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // get the token from a service const token: string = this.currentUserService.token; // add it if we have one if (token) { req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) }); } // if this is a login-request the header is // already set to x/www/formurl/encoded. // so if we already have a content-type, do not // set it, but if we don't have one, set it to // default --> json if (!req.headers.has('Content-Type')) { req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') }); } // setting the accept header req = req.clone({ headers: req.headers.set('Accept', 'application/json') }); return next.handle(req); }}
Its a pretty nice upgrade!