Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests: the
XMLHttpRequest
interface and the fetch()
API.
The
HttpClient
in @angular/common/http
offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest
interface exposed by browsers. Additional benefits of HttpClient
include testability features, typed request and response objects, request and response interception, Observable
apis, and streamlined error handling.
How to Setup in Angular4 and 5
Before you can use the
HttpClient
, you need to import the Angular HttpClientModule
. Most apps do so in the root AppModule
.import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// import HttpClientModule after BrowserModule.
HttpClientModule,
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
Having imported
HttpClientModule
into the AppModule
, you can inject the HttpClient
into an application class as shown in the following ConfigService
example.import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
0 comments:
Post a Comment