Angular 4.3 introduces a new easier way to handle HTTP requests with the HttpClient library. It’s available under a new name to avoid causing breaking changes with the current Http library.
HttpClient basically performs HTTP requests and also gives us advanced functionality like the ability to listen for progress events and interceptors to monitor or modify requests or responses.
This service is available as an injectable class, with methods to perform HTTP requests. Each request method has multiple signatures, and the return type varies based on the signature that is called (mainly the values of observe
and responseType
).
It comes with all HTTP methods required.
Sample Angular HttpClient Usage;
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment as env } from '@env'; import { Observable } from 'rxjs'; @Injectable() export class ApiClient { baseUrl = env.api.url; constructor(public http: HttpClient) {} get<T>(path: string, params?: any): Observable<T> { return this.http.get<T>(`${this.baseUrl}/${path}`, { params: params }); } post<T>(path: string, params?: any): Observable<T> { return this.http.post<T>(`${this.baseUrl}/${path}`, params, { }); } put<T>(path: string, params?: any): Observable<T> { return this.http.put<T>(`${this.baseUrl}/${path}`, params, { }); } delete<T>(path: string, params?: any): Observable<T> { return this.http.delete<T>(`${this.baseUrl}/${path}`, { params: params }); } }