Angular HTTP GET Example using httpclient

This guide explains how to make HTTP GET requests using the HttpClient module in Angular. The Angular introduced the HttpClient Module in Angular 4.3. It is part of the package @angular/common/http.  In this tutorial, let us build an HTTP GET example app, which sends the HTTP Get request to GitHub repository using the GitHub API.

HTTP Get Example

Create a new Angular App.

Import HttpClientModule

To make HTTP Get request, we need to make use of the HttpClientModule, which is part of the package @angular/common/http. Open the app.module.ts and import it. Also, import the FormsModule

You must also include it in the the imports array as shown below.

Model

Create repos.ts file and add the following code. This is a simplified model for the GitHub repository.

HTTP GET Service

Let us create a service to handle the HTTP Request. Create a new file github.service.ts and copy the following code.

First, we import the required libraries. The HttpClient is the main service, which Performs the HTTP requests like GET, PUT, POST, etc. We need to inject this into our GitHubService. Also, import HttpParams which helps us to add Query Parameters in an HTTP Request. Import HTTP Headers using the HttpHeaders which allows us to add HTTP Headers to the request.

The HttpClient service makes use of RxJs observable, Hene we import Observable, throwError & RxJs Operators like map & catchError

The URL endpoint is hardcoded in our example, But you can make use of a config file to store the value and read it using the APP_INITIALIZER token

We inject the HttpClient using the Dependency Injection

Finally, we use the get method of the httpclient to make an HTTP Get request to GitHub.

The https://api.github.com/users/<username>?repos endpoint returns the list of Repositories belonging to the user <userName>

Note that httpclient.getmethod returns the observable. Hence we need to subscribe to it to get the data.

Component

The following is the code from app.component.ts

We subscribe to the getRepos() method in our component class. Only when we subscribe to the observable, the HTTP GET request is sent to the back end server.

When we subscribe to any observable, we optionally pass the three callbacks. next(),  error()  &  complete().

Next() callback is where we get the result of the observable. In this example the list of repositories for the given user.

The observable can also result in an error. It will invoke the error() callback and pass the error object. The observables stop after emitting the error signal.

When the observable completes, it will call the complete() callback. There is no need for this call back as the subscription completes when the data is received.

Loading Indicator

We create a variable loading=true just before subscribing to the GETrequest. When the observable completes or an error occurs, we make it false. This helps us to show some kind of loading indicator to users, while we wait for the response.

Template

The template is very simple

We first ask for the userName. We use the two-way data binding to sync userName [(ngModel)]="userName" with the userName property in the component class.

getRepos() method subscribes to the HTTP get method.

We show a loading message until the observable returns response or an error.

Show the error message.

The last line shows the response as it is received.

HTTP Get in Action

Now, run the app, you should able to make a successful GET Request.

Get Syntax

The above code is a very simple example of the HTTP get() method. The complete syntax of the get() method is as shown below. It has second argument options, where we can pass the HTTP headers, parameters, and other options to control how the get() method behaves.

  • headers : use this to send the HTTP Headers along with the request
  • params: set query strings / URL parameters
  • observe: This option determines the return type.
  • responseType: The value of responseType determines how the response is parsed.
  • reportProgress: Whether this request should be made in a way that exposes progress events.
  • withCredentials: Whether this request should be sent with outgoing credentials (cookies).

observe

The GET method returns one of the following

  1. Complete response
  2. body of the response
  3. events.

By default, it returns the body as shown in our example app.

Complete Response

The following code will return the complete response and not just the body

The complete response is as follows.

events

You can also listen to progress events by using the { observe: 'events', reportProgress: true }. You can read about observe the response

Response Type

The responseType determines how the response is parsed. it can be one of the arraybuffer, json blob or text. The default behavior is to parse the response as JSON.

Strongly typed response

Instead of any, we can also use a type as shown below

String as Response Type

The API may return a simple text rather than a JSON. Use responsetype: 'text' to ensure that the response is parsed as a string.

Catching Errors

The API might fail with an error. You can catch those errors using catchError. You either handle the error or throw it back to the component using the throw err

Read more about error handling from Angular HTTP interceptor error handling

Transform the Response

You can make use of the map, filter RxJs Operators to manipulate or transform the response before sending it to the component.

URL Parameters

The URL Parameters or Query strings can be added to the request easily using the HttpParams option. All you need to do is to create a new HttpParams class and add the parameters as shown below.

The above code sends the GET request to the URL https://api.github.com/users/tektutorialshub/repos?sort=description&page=2

The following code also works.

HTTP Headers

You can also add HTTP Headers using the HttpHeaders option as shown below. You can make use of the Http Interceptor to set the common headers.

Send Cookies

You can send cookies with every request using the withCredentials=true as shown below. You can make use of the Http Interceptor to set the withCredentials=true for all requests.

Summary

This guide explains how to make use of HTTP get in Angular using an example app. In the next tutorial, we will look at the HTTP post method.

8 thoughts on “Angular HTTP GET Example using httpclient”

  1. I’m facing issues in downloading files as Zip using angular 13.
    It downloads as zip but looks like zip file gets corrupted.

    But the zip file has size. Any help is much appreciated.

  2. This tutorial is nothing but excellent. Thanks for the good work!
    For those who have not gone through the introduction to HttpModule your application might throw an error because the missing providers [] declaration in either the component or the ngModule class

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top