In this tutorial, we'll guide you through the process of fetching data from an API and displaying it in an HTML table using Angular 14. APIs are an essential part of modern web development, and being able to extract data from them is a crucial skill for any developer. We'll cover the basics of working with APIs in Angular, including setting up the HttpClientModule, defining an API endpoint, and handling HTTP requests. With practical examples and detailed explanations, you'll learn how to build powerful web applications that can consume data from any API.
Use the following steps to get/fetch data from APIs and display it in the table in angular 14 apps:
First of all, open your terminal and execute the following command on it to install angular app:
ng new my-new-app
Visit src/app directory and open app.module.ts file. Then import modules into it; as follows:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Create simple html for displaying a list using api services in angular apps. So, visit src/app/app.component.html and update the following code into it:
<h1>Angular 14 HttpClient for Sending Http Request Example</h1>
<ul class="list-group">
<li
*ngFor="let post of posts"
class="list-group-item">
{{ post.title }}
</li>
</ul>
Open a terminal and execute the following command into it to create service for http client request; as follows:
ng g s services/post
Then visit the src/app/ directory and open post.service.ts. Then add the following code into post.service.ts file:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostService {
private url = 'http://jsonplaceholder.typicode.com/posts';
constructor(private httpClient: HttpClient) { }
getPosts(){
return this.httpClient.get(this.url);
}
}
Visit the src/app directory and open app.component.ts. Then add the following code into component.ts file:
import { Component, OnInit } from '@angular/core';
import { PostService } from './services/post.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts:any;
constructor(private service:PostService) {}
ngOnInit() {
this.service.getPosts()
.subscribe(response => {
this.posts = response;
});
}
}
In this step, execute the following commands on terminal to start angular app:
ng serve
Open your web browser, type the given URL into it: as follows:
http://localhost:4200
In this tutorial, you have learned how to get/fetch data from APIs and display it in the table in angular 14 apps.