In Angular 4.3 the new HttpClientModule has been introduced. This new module is available in package @angular/common/http and a complete re-implementation of the former HttpModule. The new HttpClient service is included in HttpClientModule and can be used to initiate HTTP request and process responses within your application.
Let’s see how to use the new HttpClient in your Angular 4.3 project.
Making HttpClient Available In The Project
To be able to use the HttpClient service within your components we first need to include the HttpClientModule in the Angular application. First we need to import HttpClient module in the application’s root module in file app.module.ts:
<code>
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
</code>
Once imported you can make use of HttpClient in your components. To make HttpClient available in the component class you need to inject it into the class constructor like you can see in the following:
<code>
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; constructor(private http: HttpClient){ } }
</code>
HttpClient will use the XMLHttpRequest browser API to execute HTTP request. In order to execute HTTP request of a specific type you can use the following methods which corresponds to HTTP verbs:
- get
- post
- put
- delete
- patch
- head
- jsonp
Using HttpClient To Request Data
Let’s implement a simple example which uses GitHub’s REST API to request user data. Insert the following code in file app.component.ts:
<code>
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'app'; results = ''; constructor(private http: HttpClient){ } ngOnInit(): void { this.http.get('https://api.test.com/users) .subscribe(data => { console.log(data); }); } }
</code>