Understanding Communication with Backend Services Using HTTP
This is a small guide to introduce the use of Angular's HTTP client.
Most frontend applications need to communicate with a server using the HTTP protocol. Angular provides an HTTP client API for Angular applications through the HttpClient service class HttpClient in @angular/common/http.
Setting Up Communication with the Server
Before using HttpClient, it needs to be added to the root dependency injector of the application. Simply access app.config.ts and add HttpClientModule to the providers array as follows:
import { ApplicationConfig } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { importProvidersFrom } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
importProvidersFrom(HttpClientModule),
]
};
Now you can easily inject the HTTP client as a dependency in a class as shown in the following example:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ConfigService {
constructor(private http: HttpClient) { }
}
Requesting Data from the Server
To request data from the server, use the HttpClient.get() method. This is an HTTP request to the server that returns an Observable. The get(url, options) method takes two arguments: the endpoint URL string and an optional options object to configure the request.
options: {
headers?: HttpHeaders | {[header: string]: string | string[]},
observe?: 'body' | 'events' | 'response',
params?: HttpParams|{[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>},
reportProgress?: boolean,
responseType?: 'arraybuffer'|'blob'|'json'|'text',
withCredentials?: boolean,
}
Presenting Data Within a Component
To request data from a service within a component, you can do the following:
constructor(private configService: ConfigService) {}
showConfig() {
this.configService.getConfig()
.subscribe(data => this.config = {
heroesUrl: data.heroesUrl,
textfile: data.textfile,
date: data.date,
});
}
In this example, the component injects ConfigService into its constructor and provides a showConfig() method. Since getConfig returns an Observable of the data, the component subscribes to the return method.