How to Fetch Data using the provideHttpClient in Angular
Tags: angular, typescript, javascript, webdev
Published: 2023-07-01 12:47:01

---
title: How to Fetch Data using the provideHttpClient in Angular
published: true
description: Learn how to use the provideHttpClient in Angular to Fetch Data from a REST API
tags: angular, typescript, javascript, webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1mmer81swla4ne3tblnt.png
---

The Angular echo system has been undergoing some changes over the past year. One of those changes was the introduction of the concept of Standalone applications, which was introduced in Angular v14. The Standalone applications provide the option of creating projects without modules. We can call such applications module-less applications, which allows the possibility of only importing the packages needed for building an application. 

To fetch data in a Standalone application, Angular introduced the concept of using the `provideHttpClient`. In a module-based application the `HttpClientModule` remains the way to go. In the next few steps, I will break down how we can use the `provideHttpClient` to fetch data from a public REST API.

## Prerequisites

This tutorial requires you to be familiar with the basics of the technologies listed below:

-  Html
-  JavaScript
-  TypeScript
-  node package manager (npm)

## Table of Contents

- [How to Install and Create a Standalone app in Angular 16](#how-to-install-and-create-a-standalone-app-in-angular-16)
- [Generating the Angular service](#generating-the-angular-service)
- [How to Configure the provideHttpClient](#how-to-configure-the-providehttpclient)
- [Integrating the JSON Placeholder REST API](#integrating-the-json-placeholder-rest-api)
- [Displaying the Data in an HTML Table](#displaying-the-data-in-an-html-table)
- [Conclusion](#conclusion)

You can also watch the video version of this article on my [YouTube channel](https://youtu.be/_PXwI8ogKCs):

{% embed https://youtu.be/_PXwI8ogKCs %}

## How to Install and Create a Standalone App in Angular 16

To create a new Angular project, we need to ensure we have Angular installed in the terminal. To do that, we have to open the terminal and run the command `ng version`. If you get an error message, that means Angular has not been installed on your machine and you'll have to run the following command below to have it installed:

```terminal
npm install -g @angular/cli

```
Once the installation is complete, you can close and reopen the terminal, and then re-run the `ng version` command. That should give us the result below in the terminal:
![Angular Version](https://res.cloudinary.com/dz4tt9omp/image/upload/v1687111168/angular-version.png)
From the image above, we can see the version of the Angular version installed, which is Angular 16 as of the time of writing of this article.

Next, we can proceed to create a new standalone application in our terminal by running the following command:
```terminal
ng new ng-client --routing=false --style=css --standalone
```
The command above will generate a new standalone application called **ng-client**. The application will be without a routing configuration as we set it to false, and a style sheet of CSS. To run this application, we can navigate to the **ng-client** directory and run the `ng serve --open` command. This should open up the default Angular template user interface as seen below.
![Angular Template](https://res.cloudinary.com/dz4tt9omp/image/upload/v1687439085/ng-template.png)
## Generating the Angular service
Services in Angular are TypeScript classes that help to perform specific functions in an Angular application. In this application, we will be making use of the Angular Service to fetch data from a REST API. To do this, the first thing we need to do is to generate an Angular Service, with the following command:
```terminal
ng g service service/data
```
With the above, a new Service called `DataService` is created inside a service folder. 
## How to Configure the provideHttpClient
To configure the Angular Service, we head to the `main.ts` file. Here we can have the following code below:
```javascript
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { provideHttpClient } from '@angular/common/http';

bootstrapApplication(AppComponent, {
  providers: [provideHttpClient()],
}).catch((err) => console.error(err));
```
To summarize the above code, we
-    Start by importing the `provideHttpClient` from the `@angular/common/http` package.
-    Next, we inject the `provideHttpClient()` within the `providers` array. 

This configuration now makes it possible to make use of the `HttpClient` to communicate with the REST API in our `DataService` file.

## Integrating the JSON Placeholder REST API
The public REST API we will use in this tutorial is called the [JSON Placeholder](https://jsonplaceholder.typicode.com/). To integrate this API, we need to import a couple of packages in our `DataService` file:
```javascript
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
```
Next, we create the interface that helps to shape the way the object from our data is going take, as seen below:
```javascript
interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}
```
The `user id`, `id`, `title`, and `body` are all data we intend to display in the table. We can now create the variable that holds the link of our REST API as well as inject the `HttpClient` in the constructor.
```javascript
apiUrl = 'https://jsonplaceholder.typicode.com/posts';

constructor(private http: HttpClient) {}
```
Finally, we create the function that communicates with the REST API as seen below:
```javascript
getAllPosts(): Observable<Post[]> {
 return this.http.get<Post[]>(this.apiUrl);
}
```
-    The `getAllPosts()` is appended to an `Observable` of type `Post`.
-    In the `return` statement, we make use of the `get` http request to retrieve data from the API.

Our `DataService` file should now look like this:

```javascript
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

@Injectable({
  providedIn: 'root',
})
export class DataService {
  apiUrl = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) {}

  getAllPosts(): Observable<Post[]> {
    return this.http.get<Post[]>(this.apiUrl);
  }
}
```

With this configuration, we can now communicate with the service directly from our component file by making use of dependency injection.
## Displaying the Data in an HTML Table
To display the data on a table, we head to our `app.component.ts` file. Here we implement the following code below:
{% gist https://gist.github.com/desoga10/a22be89dd5e7371a0a902b300dbf201f %}
- We begin by importing the `DataService` in **line 3**, and then injecting it in the constructor in **line 24**.
- Next, we created the interface called `Post` between **line 5** and **line 11**. 
- In **line 21** and **line 22**, we created two variables. The first variable called `posts`, which is assigned a type of `Post`, has an initial value of an empty array(`[]`). This variable will hold the data fetched from the REST API. The second variable called `errorMessage` will hold our error message, if any exists.
- Finally, within our `ngOnInit` lifecycle hook we implement the logic to consume the data from our `DataService`. In **line 27**, we called the `getAllPosts()` function from our DataService. We then subscribed to the `getAllPosts()` function, returning two `Observers` from the subscription. The first `Observer` is called `next` in **line 28**. Here we called the `posts` variable we created earlier in **line 21**, and attached the data from the next argument to it, which is also called **posts**.
Next, in **line 32**, we created the error `Observer` and then attached any possible error that may occur to the `errorMessage` variable.

With this implementation, if we save all the files and then run the `ng serve --open` command, a new tab will open in the browser. In our `app.component.ts` file, we have a `console.log` method in **line 30**, which allows us to view the data when we open the console as seen in the image below:
![Data in the console](https://res.cloudinary.com/dz4tt9omp/image/upload/v1687966689/data.png)
To display the data in the console inside of a table, we head to the `app.component.html`, clear the boilerplate code and then paste the code below:
```javascript
<table>
  <tr>
    <th>id</th>
    <th>title</th>
    <th>body</th>
  </tr>
  <tr *ngFor="let post of posts">
    <td>{{post.id}}</td>
    <td>{{post.title}}</td>
    <td>{{post.body}}</td>
  </tr>
  <tr>
</table>
```
Above, we made use of the `*ngFor` directive within the `tr` tag to loop through the data. We then made use of interpolation(`{{}}`) to display data for the `id`, `title`, and the `body`. 

If we save, we can now have the results below in the browser:
![Display data in the table](https://res.cloudinary.com/dz4tt9omp/image/upload/v1687966944/data-in-browser.png)

## Conclusion
In this tutorial, you have learned how to fetch data for standalone applications by making use of the `provideHttpClient` in Angular. If you want access to the code base, you can either fork or clone the repo here on [Github](https://github.com/desoga10/ng-client). 

If you find this article helpful, you can kindly show your support by subscribing to my [YouTube channel](https://www.youtube.com/@TheCodeAngle) where I create awesome tutorials on web development technologies like JavaScript, React, Angular, Node.js, WordPress, and more.