Angular HttpClient is the new HTTP client of Angular since version 4.3 from the @angular/common/http package. It is an upgraded version of the former @angular/http package. Unlike the former deprecation, HttpClient responses can be typed and are JSON parsed automatically. You can also use interceptors on the immutable response and request.
The HttpClient
class from @angular/common/http
(which was introduced in Angular v4) is the newer implementation of the deprecated former Http
class from @angular/http
.
HttpClient
provides the ability to specify the return type of an HTTP request. See below for an example:
export interface Food {
name: string;
type: 'fruit' | 'dairy' | /* ... */;
}
// ...
@Component({ /* ... */ })
export class AppComponent {
foods: Observable<Food[]>;
constructor(private http: HttpClient) {
// Specify the return type using the first union type
this.foods = http.get</* specify return type here */Food[]>('https://example.com/foods.json');
}
}
<ul *ngFor="let food of foods | async">
<li>
<p><strong>Name</strong>: {{ food?.name }}</p>
<p><strong>Type</strong>: {{ food?.type | titlecase }}</p>
</ul>
foods.json
:
[
{
name: 'Banana',
type: 'fruit'
},
{
name: 'Apple',
type: 'fruit'
},
{
name: 'Milk',
type: 'diary'
},
...
]
It also adds the ability for HTTP interceptors, which:
...inspect and transform HTTP requests from your application to the server [and vice versa] - Angular - HttpClient
See Write an interceptor for more info.
For more detailed documentation about the HttpClient
, see the Angular - HttpClient guide.