Difference between HttpModule and HttpClientModule
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.
Simply about new HttpClient in Angular
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',