Angular HTTP Client

Angular HTTP Client

Most modern applications need to communicate with backend servers to fetch, save, or delete data.

Angular provides a robust, highly optimized module specifically designed for this called HttpClientModule.

It is built heavily on RxJS Observables, making asynchronous data management incredibly elegant.


Setup: Importing HttpClientModule

Before you can make network requests, you must enable the HTTP capabilities in your application.

You do this by importing HttpClientModule into your main app.module.ts file and adding it to the imports array.

Once imported globally, you can inject the HTTP client service into any file.


Making a GET Request

As we learned in the previous chapter, data fetching logic should be placed inside a Service, not a Component.

To make an HTTP request, you simply inject Angular's HttpClient into your service's constructor.

HTTP GET Example:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' }) export class ApiService {

// Injecting the HttpClient into our custom service constructor(private http: HttpClient) {}

getUsers() { // Makes a GET request to the provided URL endpoint return this.http.get('https://api.example.com/users'); } }


Subscribing to Observables

There is a massive catch: calling this.http.get() does absolutely nothing on its own!

Angular HTTP methods return RxJS Observables, which are "cold" by default.

A network request will not actually be fired until a component subscribes to that Observable.

Subscribing to Data:

export class UserListComponent implements OnInit {
  users: any = [];

constructor(private apiService: ApiService) {}

ngOnInit() { // The network request fires the moment we call .subscribe() this.apiService.getUsers().subscribe(data => { // We receive the data and assign it to our component variable this.users = data; }); } }


Exercise 1 of 2

?

What module must be explicitly imported into the AppModule before you can make any network requests in Angular?

Exercise 2 of 2

?

Because Angular HTTP requests return Observables, what method must you call to actually execute the request and receive the data?