Before you can use 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 {}
You can then inject the HttpClient
service as a dependency of 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) { } }
The HttpClient
service makes use of observables for all transactions. You must import the RxJS observable and operator symbols that appear in the example snippets. These ConfigService
imports are typical.
import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators';
You can run the live example that accompanies this guide.
The sample app does not require a data server. It relies on the Angular in-memory-web-api, which replaces the HttpClient module's
HttpBackend
. The replacement service simulates the behavior of a REST-like backend.Look at the
AppModule
imports to see how it is configured.
© 2010–2023 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://angular.io/guide/http-setup-server-communication