Logo
Published on

Fetching Data from an API in Angular

Authors

As a developer, your job often involves creating web applications that interact with external data sources.

This tutorial will guide you through the process of fetching data using Angular, a popular front-end framework, and the JSONPlaceholder API as the source of data.

We will use the Comments API from JsonPlaceholder for this article.

Let's get started with building a comment viewer using Angular and the JSONPlaceholder API.

Step 1: Create a New Angular Project

Generate a new Angular project named comment-viewer or any project name of your choice.

ng new comment-viewer

Navigate to the project folder:

cd comment-viewer

Step 2: Create an Interface for Comments

To make our code more maintainable and type-safe, we'll define an interface that represents the structure of comment objects. Create a new file named comment.interface.ts in the src/app folder with the following content:

export interface Comment {
  postId: number
  id: number
  name: string
  email: string
  body: string
}

This interface defines the shape of a comment object, specifying its properties and their data types.

Step 3: Create a Comment Service

Generate a service to handle comment data:

ng generate service comment

Update the comment.service.ts file:

comment.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Comment } from './comment.interface'; // Import the Comment interface

@Injectable({
 providedIn: 'root',
})
export class CommentService {
 private baseUrl = 'https://jsonplaceholder.typicode.com';

constructor(private http: HttpClient) {}

getComments(): Observable<Comment[]> {
 return this.http.get<Comment[]>(`${this.baseUrl}/comments`);
 }
}

With this change, we're importing the Comment interface and specifying that the getComments method returns an Observable of an array of Comment objects.

Note: You have to import HttpClientModule from [@angular/common/http](https://angular.io/api/common/http) to make this service work as expected.

you can import this module in app.module.ts

import { HttpClientModule } @angular/common/http

Step 4: Create a Comment Component

Generate a component to display comments:

ng generate component comment-list

Update the comment-list.component.ts file:

comment-list.component.ts
import { Component, OnInit } from '@angular/core'
import { CommentService } from '../comment.service'
import { Comment } from '../comment.interface' // Import the Comment interface

@Component({
selector: 'app-comment-list',
templateUrl: './comment-list.component.html',
styleUrls: ['./comment-list.component.css'],
})
export class CommentListComponent implements OnInit {
comments: Comment[] = [];

constructor(private commentService: CommentService) {}

ngOnInit(): void {
this.commentService.getComments().subscribe((comments) => {
this.comments = comments;
});
}
}

By importing the Comment interface, we ensure that the comments array in our component contains objects that match the expected structure.

Step 5: Display Comments in the Template

Update the comment-list.component.html file:

comment-list.component.html
<div class="comment-list">
 <h2>Comments</h2>
 <table>
 <thead>
 <tr>
 <th>ID</th>
 <th>Name</th>
 <th>Email</th>
 <th>Body</th>
 </tr>
 </thead>
 <tbody>
 <tr *ngFor="let comment of comments">
 <td>{{ comment.id }}</td>
 <td>{{ comment.name }}</td>
 <td>{{ comment.email }}</td>
 <td>{{ comment.body }}</td>
 </tr>
 </tbody>
 </table>
</div>

Step 6: Styling the Comment List

Add the following CSS code to the Comment List Component

comment-list.component.css
.comment-list {
margin: 20px;
}

table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}

th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}

th {
background-color: #f2f2f2;
}

Step 7: Run the Application

Start the development server:

ng serve

Open your browser and go to <http://localhost:4200/> to see the comment viewer in action.

That's it! We did it!

You can also Watch This Video

YouTube video Teaching how to fetch data from a server and show data in tables.

Conclusion

In this tutorial, you've learned how to create an Angular service to fetch data from an API, create a component to display the data and style your application for a polished look.

This is just the beginning of what you can achieve with Angular. You can further enhance this project by adding features like pagination, searching etc. Happy coding!

You can ask me any questions if you have any.

What creative ways can you think of to implement user-generated reactions (e.g., likes, dislikes) for comments in this application?