Angular 18 HttpClient Get with Examples

Angular 18 HttpClient Get with Examples

Angular's HttpClient module is part of the @angular/common/http package and is designed to simplify the process of making HTTP requests. It provides a streamlined API for sending HTTP requests and handling responses, with built-in support for various HTTP methods, such as GET, POST, PUT, DELETE, and more.

In this article, we'll learn how to use the get() method of HttpClient to send GET requests.

Key Features of HttpClient

  1. Type-Safe Requests and Responses: HttpClient allows you to specify the expected response type, ensuring that your application handles data correctly.
  2. Interceptors: You can configure request and response interceptors for logging, authentication, error handling, etc.
  3. Observable-Based: HttpClient methods return Observables, allowing you to leverage RxJS operators for powerful asynchronous programming.
  4. Simplified Configuration: Easily configure headers, parameters, and other request options.

How to Import HttpClient

To use HttpClient in your Angular 18 application, you need to import and provide HttpClient in your application's configuration file. Open the src/app/app.config.ts file and update it as follows:

import { ApplicationConfig } from '@angular/core';
[...]
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [..., provideHttpClient()]
};

HttpClient Get Request

The HttpClient is an injectable class designed to handle HTTP requests, leveraging various methods such as the HttpClient.get() method. Within an Angular 18 application, invoking HttpClient.get() initiates an HTTP request to the server, fetching data via an API.

Upon a successful request, the server responds with an observable type response. Notably, observables are inherently lazy; without subscription, the service remains inactive. Subscribing to this observable object triggers an HTTP GET request to be dispatched to the server.

Syntax of HttpClient Get Method

get(url: string, options: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: HttpObserve;
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
    withCredentials?: boolean;
} = {}): Observable 

In the provided syntax, as per Angular documentation, the get() method accepts two arguments: the endpoint URL and an options object. Below, we'll delve into the details of each parameter:

  • url: This parameter denotes the API endpoint URL, specifying where the HTTP GET request will be sent.

  • options: The second argument is an object type, comprising HTTP options to be included in the request.

    • headers: A property of type HttpHeaders, allowing configuration of header information for the HTTP GET request.
    • observe: Determines the desired response type, whether it's the complete response, the body only, or events only.
    • params: An attribute of type HttpParams, facilitating the inclusion of parameters in the URL for HTTP GET requests.

How to Call HttpClient Get Method by Example

To demonstrate how to use the HttpClient get() method in Angular 18, let's consider an example where we fetch data from a REST API. Here's a step-by-step guide:

To fetch movie data from an external API and manage API interactions efficiently, we'll create a service in Angular. This service will use HttpClient to make HTTP requests to a movie database API.

Step 1: Generate the Movies Service

First, head to a terminal and run the following command to generate a new service:

ng g s services/movies

This command creates a new service file (movies.service.ts) in the src/app/services directory.

Step 2: Generate Environment Variables

Next, generate the environment variables files using the Angular CLI:

ng g environments

This command creates environment configuration files in the src/environments directory.

Step 3: Add API Key to Environment Variables

Open the src/environments/environment.development.ts file and add your API key for accessing the movie database:

export const environment = {
    apiKEY: 'dadb019730c0075868955d1ec94040bb'
};

Make sure to replace 'dadb019730c0075868955d1ec94040bb' with your own API key.

Step 4: Provide HttpClient in App Configuration

To use HttpClient in your Angular 18 application, you need to provide it in your application's configuration. Open the src/app/app.config.ts file and add the following code:

// [...]
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [..., provideHttpClient()]
};

Step 5: Implement the Movies Service

Now, let's implement the methods to fetch movie data in the MoviesService. Open the src/app/services/movies.service.ts file and start by adding the following imports:

import { Injectable, inject } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { Movie, Movies } from '../models/movie';
import { map } from 'rxjs';
import { Videos } from '../models/video';
import { Credits } from '../models/credit';
  • inject for injecting services.
  • environment: Imports environment variables where API key is stored.
  • HttpClient: Used to make HTTP requests to the API.
  • Movie, Movies, Videos, Credits: Interfaces defining the structure of the data returned by the API.

Defining Base URL for Movie Images

Next, define and export the base URL for fetching movie images from the API.

export const imagesBaseUrl = 'https://image.tmdb.org/t/p/';

Initializing Variables and Injecting HttpClient

Next, define the following variables and inject HttpClient:

export class MoviesService {
  private apiUrl = 'https://api.themoviedb.org/3';
  private apiKey = environment.apiKEY;
  private httpClient = inject(HttpClient);
  constructor() { }

This initializes private properties for API URL, API key, and an instance of HttpClient.

Getting Movies by Type

Next, define the fetchMoviesByType method:

  fetchMoviesByType(type: string, pageNumber = 1) {
    return this.httpClient
      .get<Movies>(`${this.apiUrl}/movie/${type}?page=${pageNumber}&api_key=${this.apiKey}`)
  }

This method will be used to fetch movies of a specific type (e.g., popular, top-rated) from the API. It accepts type (e.g., 'popular', 'top_rated') and pageNumber as parameters and constructs the API URL with the specified type and page number and makes an HTTP GET request using HttpClient.

Getting Similar Movies

Next, define the fetchSimilarMovies method:

  fetchSimilarMovies(id: string) {
    return this.httpClient
      .get<Movies>(
        `${this.apiUrl}/movie/${id}/similar?api_key=${this.apiKey}`
      )
      .pipe(map((data)=> data.results));
  }

This method will be used to fetch movies similar to a specified movie by its ID. It constructs the API URL for similar movies and makes an HTTP GET request. It uses pipe and map operators from RxJS to extract the results property from the API response.

Getting Movie by ID

Next, define the fetchMovieById method:

  fetchMovieById(id: string) {
    return this.httpClient.get<Movie>(
      `${this.apiUrl}/movie/${id}?api_key=${this.apiKey}`
    )
  }

This method will be used to fetch details of a specific movie by its ID. It constructs the API URL for the movie details and makes an HTTP GET request.

Getting Movie Videos

Next, define the fetchMovieVideos method:

  fetchMovieVideos(id: string) {
    return this.httpClient
      .get<Videos>(
        `${this.apiUrl}/movie/${id}/videos?api_key=${this.apiKey}`
      )
      .pipe(map((data) => data.results))
  }

This method will be used to fetch videos (trailers, teasers) associated with a specific movie by its ID. It constructs the API URL for movie videos and makes an HTTP GET request. It uses pipe and map operators to extract the results property from the API response.

Getting Movie Cast

Finally, define the fetchMovieCast method:

  fetchMovieCast(id: string) {
    return this.httpClient
      .get<Credits>(
        `${this.apiUrl}/movie/${id}/credits?api_key=${this.apiKey}`
      )
      .pipe(map((data) => data.cast))
  }

This method will be used to fetch the cast (actors) of a specific movie by its ID. It constructs the API URL for movie credits and makes an HTTP GET request. It uses pipe and map operators to extract the cast property from the API response.

This MoviesService provides methods to fetch various movie-related data from an external API. It encapsulates the logic for making HTTP requests and handling API responses, allowing other parts of the application to easily consume and utilize movie data.

Conclusion

In conclusion, Angular's HttpClient module offers a streamlined approach to making HTTP requests in Angular 18 applications. Through its get() method, developers can easily fetch data from RESTful APIs, leveraging features such as type-safe requests, interceptors, and observables for asynchronous handling.

Key features of HttpClient include type-safe requests and responses, support for interceptors, observable-based operations, and simplified configuration options. By specifying the expected response type and configuring request options, developers can ensure efficient communication with backend servers.

To use HttpClient, it needs to be imported and provided in the application's configuration. With the provideHttpClient() function, developers can seamlessly integrate HttpClient into their Angular 18 projects.

The get() method of HttpClient initiates HTTP GET requests to server endpoints, fetching data through APIs. By subscribing to the returned observables, developers can trigger these requests and handle the server responses accordingly.

In addition to the basic usage of HttpClient for GET requests, this article also explored the syntax of the get() method, including parameters such as URL, options, headers, and response types.

Furthermore, a step-by-step example demonstrated how to implement a movie service using HttpClient to fetch movie data from an external API. This included generating environment variables, defining service methods, and utilizing RxJS operators to process API responses.

In summary, Angular's HttpClient module simplifies the process of integrating HTTP requests into Angular applications, providing developers with a powerful tool for interacting with backend servers and fetching data efficiently.


  • Date: