Which one to use to build a mock web service to test the Angular 4 app?
The HttpClientModule is a service module provided by Angular that allows us to perform HTTP requests and easily manipulate those requests and their responses. It is called a service module because it only instantiates services and does not export any components, directives or pipes.
"HttpClient is an evolution of the existing Angular HTTP API, which exists alongside of it in a separate package...". The tutorial uses HttpModule and angular.io/guide/http uses HttpClientModule and neither explains when one or the other should be used or what version of Angular is needed to use what.
As of Angular 4.3. x and above, HttpClientModule is available. In the future HttpModule with its Http class will be deprecated.
This likely means that the library ( @angular/common/http ) which declares HttpClient has not been processed correctly by ngcc , or is not compatible with Angular Ivy . Check if a newer version of the library is available, and update if so.
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',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With