DEV Community

Cover image for How to Fetch Data using the provideHttpClient in Angular
deji adesoga for This is Angular

Posted on

How to Fetch Data using the provideHttpClient in Angular

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

You can also watch the video version of this article on my YouTube channel:

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:

npm install -g @angular/cli

Enter fullscreen mode Exit fullscreen mode

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
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:

ng new ng-client --routing=false --style=css --standalone
Enter fullscreen mode Exit fullscreen mode

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

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:

ng g service service/data
Enter fullscreen mode Exit fullscreen mode

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:

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));
Enter fullscreen mode Exit fullscreen mode

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. To integrate this API, we need to import a couple of packages in our DataService file:

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
Enter fullscreen mode Exit fullscreen mode

Next, we create the interface that helps to shape the way the object from our data is going take, as seen below:

interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}
Enter fullscreen mode Exit fullscreen mode

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.

apiUrl = 'https://jsonplaceholder.typicode.com/posts';

constructor(private http: HttpClient) {}
Enter fullscreen mode Exit fullscreen mode

Finally, we create the function that communicates with the REST API as seen below:

getAllPosts(): Observable<Post[]> {
 return this.http.get<Post[]>(this.apiUrl);
}
Enter fullscreen mode Exit fullscreen mode
  • 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:

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

  • 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
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:

<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>
Enter fullscreen mode Exit fullscreen mode

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

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.

If you find this article helpful, you can kindly show your support by subscribing to my YouTube channel where I create awesome tutorials on web development technologies like JavaScript, React, Angular, Node.js, WordPress, and more.

Top comments (0)